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)

阅读更多
想对作者说点什么?

博主推荐

换一批

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