Длинная подстрока без повторяющихся символов - KeyError - PullRequest
0 голосов
/ 27 февраля 2020

По заданной строке найдите длину самой длинной подстроки без повторяющихся символов.

Пример 1:

Input: "abcabcbb"
Output: 3 
Explanation: The answer is "abc", with the length of 3. 

Пример 2:

Input: "bbbbb"
Output: 1
Explanation: The answer is "b", with the length of 1.

Пример 3 :

Input: "pwwkew"
Output: 3
Explanation: The answer is "wke", with the length of 3. 
             Note that the answer must be a substring, "pwke" is a subsequence and not a substring.

Вот мой код:

class Solution:
    def lengthOfLongestSubstring(self, s: str) -> int:
        dict = {}
        b_pointer = 0
        a_pointer = 0
        maxx = 0
        for i in range(len(s)):
            if s[i] not in dict:
                dict[s[i]] = 1
                b_pointer +=1
                maxx = max(maxx,b_pointer-a_pointer)
            else:  
                del dict[s[a_pointer]]
                a_pointer +=1


        return maxx

Ошибка : KeyError: 'a'

Помощь?

1 Ответ

0 голосов
/ 27 февраля 2020

Это происходит потому, что s[a_pointer] отсутствует в словаре, когда вы пытаетесь удалить его. Вот примеры вашего словаря в каждой точке вашего l oop до того, как он выдаст ошибку времени выполнения.

dictionary

Вы можете увидеть это в последний раз Дело в том, что в словаре нет «а». Вот модифицированный принятый код.

class Solution:
def lengthOfLongestSubstring(self, s: str) -> int:
    dict = {}
    b_pointer = 0
    a_pointer = 0
    maxx = 0
    while a_pointer < len(s) and b_pointer < len(s):
        if s[b_pointer] not in dict:
            dict[s[b_pointer]] = 1
            b_pointer +=1
            maxx = max(maxx,b_pointer-a_pointer)
        else:  
            del dict[s[a_pointer]]
            a_pointer +=1


    return maxx
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...