3. Longest Substring Without Repeating Characters

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

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

Given  "abcabcbb", the answer is "abc", which the length is 3.
Given "bbbbb", the answer is "b", with the length of 1.
Given "pwwkew", 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.

To make it clear, the return type is an integer, which is the length of the longest substring, so we do not need to save the substring itself. One easy way is using a dictionary to save every character and their position in the original string, using an integer to save the start position of current substring.

class Solution(object):
    def lengthOfLongestSubstring(self, s):
        """
        :type s: str
        :rtype: int
        """
        char_dict = {}
        max_length = 0
        length = 0
        start_index = 0
        for i in range(len(s)):
            if s[i] in char_dict and char_dict[s[i]] >= start_index:
                start_index = char_dict[s[i]] + 1
                char_dict[s[i]] = i
                max_length = max(max_length, length)
                length = i - start_index + 1
            else:
                char_dict[s[i]] = i
                length += 1
        return max(length, max_length)

阅读更多
个人分类: LeetCode
想对作者说点什么? 我来说一句

没有更多推荐了,返回首页

不良信息举报

3. Longest Substring Without Repeating Characters

最多只允许输入30个字

加入CSDN,享受更精准的内容推荐,与500万程序员共同成长!
关闭
关闭