【Leetcode-算法-Python3】3. 无重复字符的最长子串

class Solution:
    def lengthOfLongestSubstring(self, s):
        """
        :type s: str
        :rtype: int
        """
        if len(s)==0:
            return 0
        loc = {}
        re = 0
        sta = 0
        for i in range(0,len(s)):
            if s[i] in loc and sta <= loc[s[i]]:    # 注意第二个条件!! 
                sta = loc[s[i]]+1                        #调整开始位置
                loc[s[i]]=i                                  #改变loc值
            else:
                loc[s[i]]=i                                  #增加新字符的位置信息
                if i-sta+1 > re:                          #compare the length (current loc - start loc)
                    re = i - sta + 1

        return re

执行用时:120 ms

猜你喜欢

转载自blog.csdn.net/aawsdasd/article/details/80484866
今日推荐