LeetCode 3 Longest Substring Without Repeating Characters (Python)

Posted by 小明MaxMing on January 7, 2020

题目

Given a string s, find the length of the longest substring without repeating characters.

解题思路

用一个指针表示子串开始的位置,使用一个字典存每个字符上次出现的位置,如果出现重复的,移动开始指针

代码

class Solution:
    def lengthOfLongestSubstring(self, s: str) -> int:
        tmp = {}
        start = res = 0
        for i, c in enumerate(s):
            if c in tmp and start <= tmp[c]:
                start = tmp[c] + 1
            else:
                res = max(res, i - start + 1)
            tmp[c] = i
        return res

视频讲解 YouTube<--欢迎点击订阅

视频讲解 bilibili<--欢迎点击订阅