題目
Write a function to find the longest common prefix string amongst an array of strings.
即找出輸入字符串數組中的最長公共前綴。如:
輸入:[‘abc’,’abd’,’abe’]
輸出:’ab’
思路
對數組中各字符串的每一位進行對比
解法 1
class Solution:
def longestCommonPrefix(self, strs):
"""
:type strs: List[str]
:rtype: str
"""
#若字符串無內容返回空
if not strs:
return ""
#zip是將各字符串每一位打包,如zip('abc','abd','abe')爲['a','a','a']['b','b','b'] ['c','d','e']
#*strs等同於將數組中各字符串分別輸入,如*strs='abc','abd','abe'
#set(['a','a','a'])='a',set(['a','b','a'])='a''b'
for i, letter_group in enumerate(zip(*strs)):
if len(set(letter_group)) > 1:
return strs[0][:i]
else:
return min(strs)
解法 2
class Solution:
def longestCommonPrefix(self, strs):
"""
:type strs: List[str]
:rtype: str
"""
if not strs:
return ""
# 找到數組中最短的字符串
shortest = min(strs,key=len)
# 將數組中其他字符串與最短字符轉諸位對比
# 若有某位不同,則返回最短字符串到該位的內容
# 若全部相同,則返回最短字符串的所有內容
for i, ch in enumerate(shortest):
for other in strs:
if other[i] != ch:
return shortest[:i]
return shortest