Skip to content

Commit 04fdfd5

Browse files
committedDec 15, 2020
feat: longest-common-prefix
1 parent 87ae0c8 commit 04fdfd5

File tree

1 file changed

+24
-1
lines changed

1 file changed

+24
-1
lines changed
 

‎str.longest-common-prefix.py

+24-1
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,29 @@ class Solution:
88
如果不存在公共前缀,返回空字符串 ""。
99
"""
1010
def longestCommonPrefix(self, strs: List[str]) -> str:
11+
if not strs: return ""
12+
str0 = min(strs)
13+
str1 = max(strs)
14+
print(str0, str1)
15+
for i in range(len(str0)):
16+
if str0[i] != str1[i]:
17+
return str0[:i]
18+
return str0
19+
20+
def longestCommonPrefixByFind(self, strs: List[str]) -> str:
21+
if not strs:
22+
return ''
23+
24+
pre = strs[0]
25+
# 遍历数组
26+
for i in range(1, len(strs)):
27+
while strs[i].find(pre) != 0:
28+
if len(pre) == 0:
29+
return ''
30+
pre = pre[:-1]
31+
return pre
32+
33+
def longestCommonPrefixByForce(self, strs: List[str]) -> str:
1134
if not strs:
1235
return ''
1336

@@ -27,4 +50,4 @@ def longestCommonPrefix(self, strs: List[str]) -> str:
2750

2851

2952
so = Solution()
30-
print(so.longestCommonPrefix(["flower","flow","flight"]))
53+
print(so.longestCommonPrefix(["flower","flew","fleght"]))

0 commit comments

Comments
 (0)
Please sign in to comment.