题目描述请点击查看LeetCode 题目描述
Python3 代码解答如下:
class Solution:
def longestCommonPrefix(self, strs):
"""
:type strs: List[str]
:rtype: str
"""
"""
思路: 假定第一个字符串是所有字符串的公共子串,循环取第一个字符串的前 i 个字符,如果所有字符串都有这个前缀,则记录。否则跳出循环,没必要继续执行下去了。
"""
result = ''
if len(strs):
#循环字符数组中第一个字符串
for i in range(0, len(strs[0])):
#记录第一个字符串的前 i+1 个字符
c = strs[0][:i+1]
#假定字符串数组中所有字符串都含有目标字符 c
hasC = True
for j in range(0, len(strs)):
if strs[j].startswith(c) == False:
hasC = False
break
if hasC == True and len(c) > len(result):
#记录最长公共前缀
result = c
else:
break
print(result)
return result