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.

Examples:

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.

 
 

Sol:

Instead of using a set to tell if a character exists or not, we could define a mapping of the characters to its index. Then we can skip the characters immediately when we found a repeated character.

The reason is that if s[j] have a duplicate in the range [i, j) with index j', we don't need to increase iilittle by little. We can skip all the elements in the range [i, j'] and let ii to be j' + 1 directly.

class Solution(object):
    def lengthOfLongestSubstring(self, s):
        """
        :type s: str
        :rtype: int
        """
        # Using HashMap
        # Time O(n)
        
        n = len(s)
        ans = 0
        # map stores the index of the current element 
        map = collections.defaultdict(int)
        
        # try to extend to the range[i, j]
        i = 0
        
        for j in range(n):
            
            if s[j]:
                i = max(i, map[s[j]])
            ans = max(ans, j - i + 1)
            map[s[j]] = j + 1
            
        return ans
原文地址:https://www.cnblogs.com/prmlab/p/7236904.html