You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
This file contains ambiguous Unicode characters that may be confused with others in your current locale. If your use case is intentional and legitimate, you can safely ignore this warning. Use the Escape button to highlight these characters.
'''
最长公共前缀
编写一个函数来查找字符串数组中的最长公共前缀。如果不存在公共前缀,返回空字符串 " " 。示例 1: 输入: [ " flower " , " flow " , " flight " ] 输出: " fl "
示例 2: 输入: [ " dog " , " racecar " , " car " ] 输出: " "
说明:所有输入只包含小写字母 a-z 。
'''
class Solution ( object ) :
def longestCommonPrefix ( self , strs ) :
"""
:type strs: List[str]
:rtype: str
"""
if len ( strs ) == 0 : # 空字符串
return " "
i = 0 # 遍历第一个字符
j = 0 # 遍历字符串
end = 0 # 前缀结尾
while j < len ( strs ) and i < len ( strs [ j ] ) :
if j == 0 : # 以第一个字符作为基准
char = strs [ j ] [ i ] # 取第一个字符的第i位
else :
if strs [ j ] [ i ] != char : # 若其他字符第i位与第一个字符第i位不同, 终止
break
if j == len ( strs ) - 1 : # 若运行到最后一个字符仍没有终止
i + = 1 # 开始检查第i+1位
j = 0 # 回到第一个字符开始新一轮循环
end + = 1 # 第i位加入前缀
else :
j + = 1 # 吉布森第一个也不是最后一个字符,就到下一个字符
return strs [ j ] [ : end ]