3. Longest Substring Without Repeating Characters Leetcode Python New season for 2016

Given a string, find the length of the longest substring without repeating characters. For example, the longest substring without repeating letters for "abcabcbb" is "abc", which the length is 3. For "bbbbb" the longest substring is "b", with the length of 1.

class Solution(object):
    def lengthOfLongestSubstring(self, s):
        """
        :type s: str
        :rtype: int
        """
        position_hash = {}
        max_length = 0
        start = 0
        for char in s:
            position_hash[char] = -1
        for index, char in enumerate(s):
            if position_hash[char] != -1:
                while start <= position_hash[char]:
                    position_hash[s[start]] = -1
                    start += 1
            if index - start + 1 > max_length:
                max_length = index - start + 1
            position_hash[char] = index
        return max_length
                
        

O(n2) time and O(n) space

你可能感兴趣的:(3. Longest Substring Without Repeating Characters Leetcode Python New season for 2016)