带有内部while循环的forloop中的python列表索引错误

2024-06-16 09:53:54 发布

您现在位置:Python中文网/ 问答频道 /正文

这是我的代码的并发版本:

from collections import Counter
class Solution:
    def minWindow(self, s: str, t: str) -> str:

        left = 0
        right = float("inf")
        ref = Counter(t)
        necessary_count = sum(ref.values())
        curr_count = 0
        curr_dict = Counter()
        slow = 0
        for i in range(0,len(s)):
            c=s[i]
            if c in ref:
                curr_dict[c]+=1
                if curr_dict[c]<=ref[c]:
                    curr_count+=1
            while curr_count == necessary_count:
                if (i-slow)<(right-left):
                    left,right = slow,i
                s = s[slow]
                if s in ref:
                    curr_dict[s]-=1
                if curr_dict[s]<ref[s]:
                    curr_count-=1
                slow+=1
        if right == float("inf"): return ''
        return s[left:right+1]


示例测试用例:

Input: S = "ADOBECODEBANC", T = "ABC"
Expected Output: "BANC"
Actual Output:""

目前,我在声明c=s[i]的地方接收并索引错误。当我执行调试器时,它会在我完成程序第一次遇到while循环后立即抛出错误。为什么我违反了s(0<=i<len(s))的索引,而forloop保持在这些约束内?这和我的while循环有关吗?你知道吗


Tags: inrightrefifcountcounterfloatleft
1条回答
网友
1楼 · 发布于 2024-06-16 09:53:54

它确实与while循环有关:

s = s[slow]

第一次运行此代码时,slow是0,s被重新分配给它的第一个字符(现在它的长度是1)。你知道吗

在for循环的下一次迭代中,c=s[i]将引发一个IndexError,因为i是1,但是len(s)现在是1。你知道吗

相关问题 更多 >