LeetCode(03)Longest Substring Without Repeating Characters

LeetCode(03)Longest Substring Without Repeating Characters_第1张图片
image.png

本题的意思是寻找没有重复字符的最大子串,并返回最大子串的长度。题目中已经给出了Example了。下面就是对问题的分析:
题目是找最大的无重复的子串,我们可以采用Python的字典,统计字符的次数,使用滑动窗口的方法进行寻找(这个滑窗法我也是第一次听说,参考了相关博客,链接在文末会贴出来)。接着我们就解释一下滑窗法:


LeetCode(03)Longest Substring Without Repeating Characters_第2张图片
image.png

建议结合代码然后看上述图进行分析,理解比较容易。附上代码:

class Solution(object):
    def lengthOfLongestSubstring(self, s):
        """
        :type s: str
        :rtype: int
        """
        start,end,ans = 0, 0, 0
        countDict = {}
        for c in s:
            end +=1
            countDict[c] = countDict.get(c, 0) +1
            while countDict[c] >1:
                countDict[s[start]] -=1
                start +=1
            ans = max(ans,end-start)
        return ans
                

以上就是本题的解题思路及代码。
参考链接
https://www.cnblogs.com/zuoyuan/p/3785840.html
http://bookshadow.com/weblog/2015/04/05/leetcode-longest-substring-without-repeating-characters/

声明:博客的撰写是为了记录自己的学习成果,文章中出现的图为自己一点点画出来的,如需转载请注明出处!!!
祝好!

你可能感兴趣的:(LeetCode(03)Longest Substring Without Repeating Characters)