題目要求
編寫一個函數(shù)來查找字符串?dāng)?shù)組中的最長公共前綴。
如果不存在公共前綴,返回空字符串 ""。
示例 1:
輸入: ["flower","flow","flight"]
輸出: "fl"
示例 2:
輸入: ["dog","racecar","car"]
輸出: ""
解釋: 輸入不存在公共前綴。
說明:
所有輸入只包含小寫字母 a-z 。
思路一
若列表不為空,取第一個元素,無所謂最長最短,只要出現(xiàn)各元素同索引字符不一致或某一元素耗盡的情況,就中斷操作,返回結(jié)果
→_→ talk is cheap, show me the code
class Solution:
def longestCommonPrefix(self, strs):
"""
:type strs: List[str]
:rtype: str
"""
if not strs:
return ""
result = ""
for i in range(0, len(strs[0])):
for j in strs[1:]:
if i >= len(j) or j[i] != strs[0][i]:
return result
result += strs[0][i]
return result
思路二
若列表不為空,利用zip拉鏈函數(shù),將各元素同索引字符組成一個元組,若這個元組中所有元素相同則為公共前綴部分,出現(xiàn)不同,即返回結(jié)果
→_→ talk is cheap, show me the code
class Solution:
def longestCommonPrefix(self, strs):
"""
:type strs: List[str]
:rtype: str
"""
if not strs:
return ""
result = ""
for item in zip(*strs):
if len(set(item)) != 1:
return result
result += item[0]
return result