Write a function to find the longest common prefix string amongst an array of strings.
Subscribe to see which companies asked this question
class Solution(object):
def longestCommonPrefix(self, strs):
"""
:type strs: List[str]
:rtype: str
"""
if len(strs) == 0:
return ''
else:
temp = strs[0]
for s in strs:
while(True):
#判断str的前缀是不是temp
if temp in s and s[:len(temp)] == temp:
break
#如果temp已经截断到空字符串,跳出
elif temp == '':
break
#截断字符串
else:
temp = temp[:-1]
#如果temp已经截断到空字符串,跳出
if temp == '':
break
return temp
是很简单的一道题,不过我在做的时候,对于一些细节和边界条件犯了一些错误,要多多认真注意