Write a function to find the longest common prefix string amongst an array of strings.
解题思路:
依次取第一个字符串的各个字符,判断剩余字符串的前缀是否包含此字符,如果全部包含,则该字符为最长公共前缀的一员;否则,前缀到此结束。
Python实现:
class Solution:
def longestCommonPrefix(self, strs):
"""
:type strs: List[str]
:rtype: str
"""
lens = len(strs)
if lens == 0:
return ''
if lens == 1:
return strs[0]
pre = ''
for i in range(len(strs[0])):
ch = strs[0][i] # 依次取第一个字符串的各个字符
count = 0
for j in range(1, lens): # 判断剩余字符串的前缀有没有包含此字符
if len(strs[j]) > i and strs[j][i] == ch:
count += 1
if count == lens - 1:
pre += ch
else:
return pre
return pre
a = ['abc','ab','abcd','a']
b = Solution()
print(b.longestCommonPrefix(a)) # a
网友评论