无重复字符的最长子串

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

 

示例 1:

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

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

输入: "pwwkew"
输出: 3
解释: 因为无重复字符的最长子串是 "wke",所以其长度为 3。
  请注意,你的答案必须是 子串 的长度,"pwke" 是一个子序列,不是子串。

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

 

方法:  滑动窗口

建立一个数组hash_作为滑动窗口,用来建立字符和字符出现位置的映射。

用两个指针start,i来记录滑动窗口的起始位置

向右侧滑动指针 i,如果它不在 hash中,我们会继续滑动i。直到 s[j] 已经存在于 hash_ 中。如果是s[j]存在于hash_

中,把开始的指针调整为s[j]在hash_中位置映射加一。

我们找到的没有重复字符的最长子字符串将会以指针start开头。

 

 

class Solution(object):
    def lengthOfLongestSubstring(self, s):
        """
        :type s: str
        :rtype: int
        """
        start = max_len = 0
        hash_ = {}
        for i in range(len(s)):
            if s[i] in hash_ and start <= hash_[s[i]]:
                start = hash_[s[i]] + 1
            else:
                max_len = max(max_len,i-start + 1)
            hash_[s[i]] = i
        
        
        return max_len

 

posted @ 2019-09-20 16:48  biu~biu~biu~  阅读(141)  评论(0编辑  收藏  举报