-
Notifications
You must be signed in to change notification settings - Fork 0
/
014_longestCommonPrefix.py
57 lines (51 loc) · 1.55 KB
/
014_longestCommonPrefix.py
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
class Solution:
def longestCommonPrefix(self, strs):
"""
:type strs: List[str]
:rtype: str
"""
mixLength = 100000000
Rstr = ''
# 注意此处,每一步基本都要先判断是否为空和列表集合是否为空
if strs == [] or strs == [""]:
return ""
# 学习如何求一个列表中,值的长度最小值。即:minl = min([len(x) for x in strs])
for i in strs:
if len(i) < mixLength:
mixLength = len(i)
for i in range(mixLength):
for j in strs:
temp = strs[0][i]
if temp != j[i]:
return Rstr
Rstr += temp
if Rstr == '':
return ""
else:
return Rstr
# 别人的
class Solution1:
def longestCommonPrefix(self, strs):
"""
:type strs: List[str]
:rtype: str
"""
if not strs:
return ""
if len(strs) == 1:
return strs[0]
minl = min([len(x) for x in strs])
end = 0
while end < minl:
for i in range(1, len(strs)):
if strs[i][end] != strs[i - 1][end]:
return strs[0][:end]
end += 1
return strs[0][:end]
if __name__ == '__main__':
strs1 = ["flower","flow","flight"]
strs2 = ["dog","racecar","car"]
strs3 = []
strs4 = ["a"]
strs5 = ["aca","cba"]
print(Solution().longestCommonPrefix(strs4))