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)

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

私密
私密原因:
请选择设置私密原因
  • 广告
  • 抄袭
  • 版权
  • 政治
  • 色情
  • 无意义
  • 其他
其他原因:
120
出错啦
系统繁忙,请稍后再试