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.
Note:
All given inputs are in lowercase letters a-z
.
思路解析:这个题我用的最常用的方法,就是两个两个比,前两个比较,得出最大相同子串,然后子串和第三个比,得出最大相同子串,以此类推。需要注意,此题还有一种情况是当输入的字符串为空时,直接return ""。
class Solution:
def longestCommonPrefix(self, strs):
"""
:type strs: List[str]
:rtype: str
"""
if len(strs):
result=strs[0]
for word in strs:
for i in range(len(result)):
if i<len(word):
if result[i]==word[i]:
continue
else:
result=result[:i]
break
else:
result=result[:i]
break
else:
result=""
return result
做完之后,发现用时比较久,然后看了标准答案和别人的答案,发现了很多很优秀的算法,比如二分查找。
另外还可以利用zip和enumerate迭代器。