编写一个函数,在字符串数组中查找最长的公共前缀字符串.索引超出范围



我正在做一个问题,我需要写一个函数来查找字符串数组中最长的公共前缀字符串。
例如:

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

我要做的是检查每个单词的每个字母,看看它们是否相等。当它们不在一起的时候,我就知道我们有最长的公共前缀。经过一段时间的头脑风暴,这是我所能做的最好的事情,我接受了这个想法。然而,一旦我完成了我的代码,它似乎对一些数组工作,但大多数时候我有一个索引超出范围的错误。我去了python可视化工具看看哪里出了问题,但每次我试图改变一些东西时,我都会得到一个索引错误,但原因不同。因此,经过几个小时的调试,我放弃了,现在我请求您帮助解决这个索引问题。例如,当我有这样一个数组时,就会出现索引错误:["ab"、";a"等等。我很确定我的想法是代码,我的代码几乎可以工作,所以我只是问如何改变它,而不是一个完整的新代码。谢谢
这是我的代码:

strs = ["ab","a"]
def longestCommonPrefix(strs):
for word in strs:
if word == "":
return ""
if len(strs) == 1:
return strs[0]
common_prefix = ""
j = 0
Common = True
while Common:
for i in range(len(strs) - 1):
if strs[i][j] != strs[i + 1][j]:
Common = False
break
else:
common_prefix += strs[0][j]
j += 1
return common_prefix
print(longestCommonPrefix(strs))
strings = ["a", "ab"]
def find_longest_prefix(data):
shortest_word = min(data, key=len)
for prefix_slice_end in range(len(shortest_word), 0, -1):
if all(i.startswith(shortest_word[0:prefix_slice_end]) for i in data):
return shortest_word[0:prefix_slice_end]
return ''
print(find_longest_prefix(strings))
# >> a

该错误是因为列表中的所有字符串的长度不相同,所以如果循环遍历一个字符串长度,可能会有一些字符串的长度小于此长度。因此,当使用if条件时,尝试阻止IndexError.

的检查。试试这个

strs = ["ab", "a"]

def longestCommonPrefix(strs):
for word in strs:
if word == "":
return ""
if len(strs) == 1:
return strs[0]
common_prefix = ""
j = 0
Common = True
while Common:
for i in range(len(strs) - 1):
try:
if strs[i][j] != strs[i + 1][j]:
Common = False
break
except IndexError:
Common = False
break
else:
common_prefix += strs[0][j]
j += 1
return common_prefix

print(longestCommonPrefix(strs))

如果你想用其他方法,那就用这个。


def longestCommonPrefix(lst):
for a in range(1, len(lst[0])):
try:
if not all(letter.startswith(lst[0][:a]) for letter in lst[1:]):
return lst[0][:a-1]
except IndexError:
return lst[0][:a-1]
return ""
lst = ["flower", "flow", "flight"]
print(longestCommonPrefix(lst))
def longestCommonPrefix(strs):
if len(strs) == 0:
return ""
current = strs[0]
for i in range(1,len(strs)):
temp = ""
if len(current) == 0:
break
for j in range(len(strs[i])):
if j<len(current) and current[j] == strs[i][j]:
temp+=current[j]
else:
break
current = temp
return current
input_list = ["school","schedule","scotland"]
print(longestCommonPrefix(input_list))

最新更新