LeetCode 3 -- longest substring without repeating characters

Posted by s4salman on Thu, 12 Dec 2019 22:04:21 +0100

1. topic

2. answers

2.1. Method I

We traverse the string from front to back, and start represents the starting position of the longest substring, which is set to zero at the beginning.

If no duplicate characters are encountered, the length of the substring is updated and traversed backward.

If a duplicate character is encountered, the start position of the update string is the next position of the previous same character, and the length of the substring is updated.

Repeat this process until the traversal is complete.

'abcabc',start = 0,str_len = 1, 2, 3
The second time 'a' is encountered, start = 1, str_len = 3
The second time 'b' is encountered, start = 2, str_len = 3
The second time 'c' is encountered, start = 3, str_len = 3

class Solution:
    def lengthOfLongestSubstring(self, s):
        """
        :type s: str
        :rtype: int
        """

        max_len = 0
        str_len = 0
        start = 0      # Starting position of the longest substring
        index = 0     # The position of the last same character in the substring is a relative position, not a position in the original string
        
        for i in range(len(s)):
            
            if (s[i] not in s[start:i]):
                str_len += 1
               
            # If a duplicate character is encountered, the start position of the update substring is the position following the previous same character
            # At the same time, we need to update the substring length
            else:
                max_len = max(max_len, str_len)
                index = s[start:i].find(s[i])
                str_len = str_len - index
                start = start + index + 1 
                
        max_len = max(max_len, str_len) # No duplicate characters have been encountered
        return max_len

2.2. Method 2

In method 1, each time we judge whether the current character is a repeating character, we need to search in the substring. When we update the starting position of the substring, we also need to search for the position of the same character in the substring. The efficiency is very low.

In fact, what we need to know is the starting position of a substring. When traversing later, we only need to update the starting position and recalculate the substring length at an appropriate time.

Therefore, we can establish a mapping between the current character and the next position of the current character.

All maps are initialized to zero, start = 0. From the front to the back, the string is traversed, and the mapping is updated to calculate the length of the substring.

If the mapping of the current character is greater than start, the start will be updated if the current character appears after satrt.

class Solution:
    def lengthOfLongestSubstring(self, s):
        """
        :type s: str
        :rtype: int
        """
        max_len = 0
        str_len = 0
        start = 0    # Start position of the longest substring
        index = 0   # The position of the repeating character in the substring
        
        # Initialize mapping
        table = []
        for i in range(128):
            table.append(0)
                
        for i in range(len(s)):
            
            start =  max(start, table[ord(s[i])])

            str_len = i - start + 1    
            max_len = max(max_len, str_len)
            
            table[ord(s[i])] = i + 1
            
        return max_len
class Solution {
public:
    int lengthOfLongestSubstring(string s) {
        
        int table[128] = {0}; // Auto initialize to zero
        int max_len = 0;
        int str_len = 0;
        int start = 0;
        
        string::iterator it = s.begin();
            
        for (int j = 0; it != s.end(); it++, j++)
        {
            start = start > table[*it] ? start : table[*it];
            table[*it] = j + 1;
            str_len = j - start + 1;
            max_len = max_len < str_len ? str_len : max_len;
        }
        
        return max_len;
    }
};

For more highlights, please pay attention to "seniusen"!

Topics: C++