leetcode -- 3.无重复字符的最长子串

内容描述:给定一个字符串,请你找出其中不含有重复字符的 最长子串 的长度。

class Solution(object):
    def lengthOfLongestSubstring(self, s):
        """
        :type s: str
        :rtype: int
        """
        #start为无重复子串开始位置的指针,maxlen为最大长度
        start = maxlen = 0
        
        #创建一个字典,key为遍历字符串s的元素,vale为其索引
        dic = {}
        
        #遍历字符串,判断该元素是否在字典中
        for i in range(len(s)):
            if s[i] in dic and start <= dic[s[i]]:
                #若在并且,无重复子串初始的位置小于已经在该字典中元素的索引,以该元素的下一个索引为start
                start = dic[s[i]] + 1
            else:#不在则说明还未重复,i-start+1为此处的索引减去无重复子串开始的位置start
                maxlen = max(maxlen, i-start+1)
            dic[s[i]]  = i
        return maxlen

猜你喜欢

转载自www.cnblogs.com/hengw/p/10423030.html