猿问

如何消除错误“列表索引超出范围”

我正在解决以下问题:

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

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

示例 1:

输入:["flower","flow","flight"]
输出:"fl"
示例 2:

输入:["dog","racecar","car"]
输出:""
解释:输入字符串之间没有公共前缀。

但结果显示在第 6 行(代码a1= strs[0])有一个错误“列表索引超出范围”这是我的代码:

class Solution:

    def longestCommonPrefix(self, strs: List[str]) -> str:

        if not strs:

            return ""

        a1= strs[0] 

        a2=strs[1]

        if a1[0]!= a2[0]:

            return ""

        elif len(strs)==2:

            new=strs[0]

            new_x=strs[1]

            xmin=min(len(strs[0]),len(strs[1]))

            for i in range(xmin):

                i=0

                if new[i]==new_x[i]:

                    i+=1

                else:

                    res=i

                    rescom=new[:res]

                    return rescom

        else:

                    j=1

                    while j<len(strs):

                        strs_new=strs[j]

                        strs_cmp=strs[j-1]

                        for k in range(0,(min(len(strs_new)-1,len(strs_cmp)-1))):

                            if strs_new[k]==strs_cmp[k]:

                                k+=1  

                            else:

                                res=k

                        j+=1

                    return strs_new[:res]


蓝山帝景
浏览 255回答 1
1回答

心有法竹

我认为您真正想要获得的是这样的:def longestCommonPrefix(strs):&nbsp; &nbsp; if not strs: return ""&nbsp; &nbsp; smallest = min([len(x) for x in strs])&nbsp; &nbsp; prefix = ""&nbsp; &nbsp; for i in range(smallest):&nbsp; &nbsp; &nbsp; &nbsp; a = strs[0][i]&nbsp; &nbsp; &nbsp; &nbsp; if all([x[i] == a for x in strs]):&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; prefix += a&nbsp; &nbsp; &nbsp; &nbsp; else: break&nbsp; &nbsp; return prefix编辑:再次查看您的代码后,您的代码无法处理 的情况strs = [""]或任何其他类似的单项列表,因为您a2=strs[1]在检查长度strs是否至少为之前调用2。
随时随地看视频慕课网APP

相关分类

Python
我要回答