美文网首页
15 - Medium - 无重复字符的最长子串

15 - Medium - 无重复字符的最长子串

作者: 1f872d1e3817 | 来源:发表于2018-04-20 14:15 被阅读0次

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

示例:

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

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

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

关键:利用一个dict记录每个字母出现的最后位置,再利用一个start记录最靠右的重复点

class Solution:
    def lengthOfLongestSubstring(self, s):
        """
        :type s: str
        :rtype: int
        """
        _max, start, d = 0, 0, {}
        for i, _s in enumerate(s):
            if _s in d and d[_s] >= start:
                start = d[_s] + 1
            d[_s] = i
            _max = max(_max, i - start + 1)
        return _max
class Solution:
    def lengthOfLongestSubstring(self, s):
        """
        :type s: str
        :rtype: int
        """
        longestLen = 0
        i = 0
        j = 0
        hashMap = {}
        for j in range(len(s)):
            if s[j] in hashMap.keys():
                i = max(hashMap[s[j]], i)
            longestLen = max(longestLen, j - i + 1)
            hashMap[s[j]] = j + 1
        return longestLen

相关文章

网友评论

      本文标题:15 - Medium - 无重复字符的最长子串

      本文链接:https://www.haomeiwen.com/subject/kegakftx.html