美文网首页
3. Longest Substring Without Rep

3. Longest Substring Without Rep

作者: 葡萄肉多 | 来源:发表于2019-11-10 15:52 被阅读0次

    Given a string, find the length of the longest substring without repeating characters.

    Example 1:

    Input: "abcabcbb"
    Output: 3
    Explanation: The answer is "abc", with the length of 3.

    Example 2:

    Input: "bbbbb"
    Output: 1
    Explanation: The answer is "b", with the length of 1.

    Example 3:

    Input: "pwwkew"
    Output: 3
    Explanation: The answer is "wke", with the length of 3.
    Note that the answer must be a substring, "pwke" is a subsequence and not a substring.

    思路

    1. 遍历字符串,过程中将出现过的字符存入字典,key为字符,value为字符下标
    2. 用maxLength保存遍历过程中找到的最大不重复子串的长度
    3. 用start保存最长子串的开始下标
    4. 如果字符已经出现在字典中,更新start的值
    5. 如果字符不在字典中,更新maxLength的值
    6. return maxLength

    代码

    class Solution:
        def lengthOfLongestSubstring(self, s: str) -> int:
            start = maxLength = 0
            charSeq = {}
            for i in range(len(s)):
                if s[i] in charSeq and start <= charSeq[s[i]]:
                    start = charSeq[s[i]] + 1
                else:
                    maxLength = max(maxLength, i - start + 1)
                charSeq[s[i]] = i
            return maxLength
    

    相关文章

      网友评论

          本文标题:3. Longest Substring Without Rep

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