刷题 最长不重复子串

版权声明:https://blog.csdn.net/CAIYUNFREEDOM https://blog.csdn.net/CAIYUNFREEDOM/article/details/91420216

https://leetcode.com/problems/longest-substring-without-repeating-characters/solution/

给定一个字符串,找出不含有重复字符的最长子串的长度。

示例:

给定 "abcabcbb" ,没有重复字符的最长子串是 "abc" ,那么长度就是3。

给定 "bbbbb" ,最长的子串就是 "b" ,长度是1。

给定 "pwwkew" ,最长子串是 "wke" ,长度是3。请注意答案必须是一个子串,"pwke" 是 子序列 而不是子串。

解题思路

遍历字符串的每个字符。

ans保存结果。

j 代表当前遍历的字符下标。i-1= s[ j ] 最后出现位置,保存在字典中。

例如,两个c中间没有其他c,没有重复字母:

....c........c.....

当前j遍历到第二c字符。则 i =( 第一个c的下标+1)。 

class Solution(object):
    def lengthOfLongestSubstring(self, s):
        """
        :type s: str
        :rtype: int
        """
        ans = 0
        dic={}
        i=0
        j=0
        for e in s:
          if dic.has_key(e):
             i = max(i, dic[e])
          ans = max(ans, j-i+1)
          j+=1
          dic[e]=j
        return ans

猜你喜欢

转载自blog.csdn.net/CAIYUNFREEDOM/article/details/91420216
今日推荐