1 Description(描述)
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: “”
Note:
All given inputs are in lowercase letters a-z.
所有给定的输入都是小写字母a-z。
2 Solution(解决方案)
如果字符串数组为空,则返回“”,否则只需要考虑最大的字符串与最小的字符串即可,然后利用最小的字符串是否在最大的字符串之中,如果存在则返回这个字符串,否则后退一个字符在判断,如果后退到最后还是不在最长的字符串中,则返回“”。
def longestCommonPrefix(m):
if not m:
return ''
m.sort()
minnum = m[0]
maxnum = m[-1]
while True:
if not len(minnum):
return ''
if maxnum.find(minnum) == 0:
return minnum
else:
minnum = minnum[:len(minnum)-1]