Write a function to find the longest common prefix string amongst an array of strings.
思路:
- 找出所有字符串共同的前綴蛮放。以第一個字符串為標的映皆,依次進行比較亡问。
- 設(shè)置共同前綴的index為0主穗,最小長度是所有字符串長度中最小的那個葡粒。依次比較strs中的元素须眷,如果不等征懈,就返回第一個字符串到index長度的slice。index加一俏扩,直至大于最小長度糜工。
#!/usr/bin/env python
# -*- coding: UTF-8 -*-
class Solution(object):
def longestCommonPrefix(self, strs):
"""
:type strs: List[str]
:rtype: str
"""
if len(strs) == 0:
return ""
longest = len(strs[0])
for e in strs[1:]:
index = 0
while index < len(e) and index < longest and strs[0][index] == e[index]:
index += 1
longest = min(index, longest)
return strs[0][:longest]
def longestCommonPrefix2(self, strs):
if len(strs) <= 1:
return strs[0] if len(strs)==1 else ""
end, minlength = 0, min([len(s) for s in strs])
while (end < minlength):
for i in xrange(1, len(strs)):
if strs[i][end] != strs[i-1][end]:
return strs[0][:end]
end += 1
return strs[0][:end]
if __name__ == '__main__':
sol = Solution()
strs = ["abcd", "abcde", "abcdef"]
strs = ["a", "b"]
print sol.longestCommonPrefix(strs)
print sol.longestCommonPrefix2(strs)