-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathlongestCommonPrefix.py
More file actions
87 lines (77 loc) · 2.15 KB
/
longestCommonPrefix.py
File metadata and controls
87 lines (77 loc) · 2.15 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
'''
Source : https://leetcode.com/problems/longest-common-prefix/
Author : Yuan Wang
Date : 2018-06-22
/**********************************************************************************
*Write a function to find the longest common prefix string amongst an array of strings.
*
*If there is no common prefix, return an empty string "".
*
*Example 1:
*
*Input: ["flower","flow","flight"]
*Output: "fl"
*Example 2:
*
*Input: ["dog","racecar","car"]
*Output: ""
*Explanation: There is no common prefix among the input strings.
**********************************************************************************/
'''
def longestCommonPrefix(strs):
"""
:type strs: List[str]
:rtype: str
"""
if not strs or not strs[0]:
return ""
start=0
end=len(strs[0])
element=strs[0][start]
result=""
while self.check_str(element,strs,start) and start<end:
result+=element
start+=1
if start<end:
element=strs[0][start]
else:
break
return result
def check_str(element,strs,start):
for i in range(1,len(strs)):
if start < len(strs[i]):
if strs[i][start] != element:
return False
else:
return False
return True
'''
Algorithm
To employ this idea, the algorithm iterates through the strings [S_1 ... S_n]
finding at each iteration ii the longest common prefix of strings LCP(S_1 ... S_i)
When LCP(S_1 ... S_i) is an empty string, the algorithm ends. Otherwise after
n iterations, the algorithm returns LCP(S_1 ... S_n)
Time complexity: O(n), Space Complexity:O(1)
'''
def longestCommonPrefix(strs):
"""
:type strs: List[str]
:rtype: str
"""
if not strs:
return ""
prefix=strs[0]
for i in range(1,len(strs)):
while indexof(strs[i],prefix) !=0:
#while strs[i].find(prefix) != 0:
prefix=prefix[0:len(prefix)-1]
if len(prefix) == 0:
return ""
return prefix
def indexof(string,substring):
try:
return string.index(substring)
except:
return -1
strs=["flower","flow","flight"]
print(longestCommonPrefix(strs))