最长公共前缀-获取运行时错误



问题:

编写一个函数,在字符串数组中查找最长的公共前缀字符串。

如果没有公共前缀,则返回一个空字符串""

示例1:

Input: strs = ["flower","flow","flight"]
Output: "fl"

示例2:

Input: strs = ["dog","racecar","car"]
Output: ""

解释:输入字符串之间没有通用前缀。

限制:

  • 1 <= strs.length <= 200
  • 0 <= strs[i].length <= 200
  • strs[i]仅由小写英文字母组成

我的代码

def longestCommonPrefix(self, s: List[str]) -> str:
st=''

for i in range(len(s[0])):
ch = s[0][i]
match = True

for j in range(1,len(s)):
lj= len(s[j])
if lj<i or ch != s[j][i]:
match = False
break
if match == False:
break
else:
st+=ch
return st

以下输入的运行时错误:

输入

["ab", "a"]

取第一个元素,在随后的元素上迭代,并确定最长前缀

def solution( strs):
if not strs:
return ""
res = strs[0]
i = 1
while i < len(strs):
while strs[i].find(res) != 0:
res = res[0:len(res) - 1]
i += 1
return res
# OUTPUT:
print(solution(["flower","flow","flight"]))  # fl
print(solution(["dog","racecar","car"]))    #
print(solution(  ["ab", "a"]))    # a

首先,您可以获得所有的出现;添加到dict&然后可以在dict上工作

你可以试试:

strs = ["flower","flow","flight"]
collect_dict = {}
for data in strs:
for d_index, d_data in enumerate(data):
# import pdb;pdb.set_trace()
inner_data = data[0:d_index + 1]
if inner_data not in collect_dict:
collect_dict[inner_data] = len([item for item in strs if item.startswith(inner_data)])
print(collect_dict)
keymax = max(zip(collect_dict.values(), collect_dict.keys()))[1]
print("max: " + keymax)

输出:

{'f': 3, 'fl': 3, 'flo': 2, 'flow': 2, 'flowe': 1, 'flower': 1, 'fli': 1, 'flig': 1, 'fligh': 1, 'flight': 1}
max: fl

最新更新