Problem: To find the longest comman prefix amongest an array of strings.
If no comman prefix, return " ".
以下是方法:
'''
第一种方法:
排序将相同多的字符串排在一起,而相同部分少的要排到首尾两端
如果存在共同部分,一定会出现在首尾两端的字符串。
防止溢出出现,比较首尾两端长度,取较短进行遍历。
'''
'''
class Solution:
def longestCommonPrefix(self, s):
if s == None:
return ""
if len(s) == 1:
return s[0]
# 先将s所有string item 排序,这样所有string item就是从a-z的排列
sorted_s = sorted(s)
common = ''
for c in sorted_s[0]: # 从第一个stringitem开始检验最后一stringitem是否有相同项
if sorted_s[-1].startswith(common+c): # startswith的方法比较检验
common += c
else:
break
return common
'''
"""
# 第二种方法: 两重的遍历搜索
class Solution:
def longestCommonPrefix(self, s):
if s == None:
return ''
if len(s) == 1:
return s[0]
same = ' '
for i in range(len(s[0])):
c = s[0][i]
for j in range(1, len(s)):
if i >= len(s[j]) or s[j][i] != c:
return same
same += c
return same
"""
# 第三种方法
# 该方法使用min() 和 max(),他们返回是按照alphabetic order 进行筛选
# 利用enumerate方法遍历min部分,比较筛选出same part
class Solution:
def longestCommonPrefix(self, s):
if not s:
return ''
s1 = min(s)
s2 = max(s)
for i, c in enumerate(s1):
if c != s2[i]:
return s1[:i]
from datetime import datetime
if __name__ == "__main__":
t0 = datetime.now()
str1 = ["flower","flirht","flow"]
str2 = ["dog","cat","racer"]
testDemo1 = Solution().longestCommonPrefix(str1)
testDemo2 = Solution().longestCommonPrefix(str2)
t1 = datetime.now()
print("runtime: ",(t1-t0).microseconds)
print("common: fl ",testDemo1)
print(" No Common")