leetcode3 无重复字符的最长子串

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

示例 1:

输入: "abcabcbb"
输出: 3
解释: 因为无重复字符的最长子串是 "abc",所以其长度为 3。
示例 2:

输入: "bbbbb"
输出: 1
解释: 因为无重复字符的最长子串是 "b",所以其长度为 1。

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/longest-substring-without-repeating-characters

解题思路, 用一个字典存字母和位置

1 标记当前起始位置,start  

2 更新字段中元素的位置 ,元素位置一定是大于等于 start 位置,如果 start 位置小于

 

class Solution(object):
    def lengthOfLongestSubstring(self, s):
        """
        :type s: str
        :rtype: int
        """
        #建立一个字典来存储字母和字母的位置
        dict1=dict()
        #存储最大长度
        maxlen=0
        # 开始遍历字符串的位置
        start=0
        for  i in range(len(s)):
            if s[i]  in dict1.keys() and start<=dict1[s[i]]:
                start =dict1[s[i]]+1
            else:
                maxlen=max(maxlen, i-start +1)
                
            dict1[s[i]]=i #更新字典中元素所在位置,一定是当前最大的index
        return maxlen

 

posted @ 2020-07-25 19:24  misaiya9  阅读(64)  评论(0)    收藏  举报