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

问题描述 投票:0回答:4

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

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))
python python-3.x string list substring
4个回答
2
投票
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

1
投票

该错误是因为 lst 中的所有字符串的长度并不相同,因此如果循环一个字符串长度,则可能有一些字符串的长度小于此长度。因此,在使用 if 条件时,尝试并 except 阻止对

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))


1
投票
   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))

0
投票

最简单最简单的方法:

# Use the first string as a reference
reference = strs[0]
for i in range(len(reference)):
    for string in strs[1:]:
        if i >= len(string) or string[i] != reference[i]:
            return reference[:i]
return reference
© www.soinside.com 2019 - 2024. All rights reserved.