LeetCode -- longest substring without duplicate characters

Posted by calevans on Sun, 03 May 2020 05:39:23 +0200

LeetCode -- longest substring without duplicate characters

Blog Description

The information in this article comes from the Internet and personal summary, which is intended to summarize personal learning and experience. If there is any infringement, please contact me to delete it. Thank you!

Explain

leetcode Question, Interview 48

The longest substring without duplicate characters

subject

Find the longest substring that does not contain duplicate characters from the string and calculate the length of the longest substring.

Example 1:

Input:'abcabcbb'
Output: 3 
Interpretation: Since the longest substring without duplicate characters is "abc", its length is 3.

Example 2:

Input:'bbbbb'
Output: 1
 Interpretation: Since the longest substring without duplicate characters is "b", its length is 1.

Example 3:

Input:'pwkew'
Output: 3
 Interpretation: Since the longest substring without duplicate characters is "wke", its length is 3.
     Note that your answer must be the length of the substring, "pwke" is a substring, not a substring.

Go Language

thinking

Traverse through the string, use map to record where duplicate elements appear, compare the length of the substring, and find the longest timely updates

Code

func lengthOfLongestSubstring(s string) int {
	//Create a map collection
	lastOccured := make(map[byte]int)
	//Counter
	startI := 0
	//length
	maxLength := 0

	//Traverse string
	for i, ch := range []byte(s) {
		//Judgement set is not empty
		if lastI, ok := lastOccured[ch]; ok && lastI >= startI {
			startI = lastI + 1
		}
		//Calculate the longest substring
		if i-startI+1 > maxLength {
			maxLength = i - startI + 1
		}
		//Record last occurrence
		lastOccured[ch] = i
	}
	return maxLength
}

Python Language

Idea one (sliding window)

  • Initialize the head and tail pointers;

  • The tail pointer moves right to determine whether the element pointed to by tail is in the window of [head:tail];

    • If the element is not present in the window, add it to the window, update the maximum window length, and move the tail pointer to the right.

    • If the element exists in the window, move the head er pointer to the right until the element is not included in the window.

  • Returns the maximum window length.

Code

class Solution:
    def lengthOfLongestSubstring(self, s: str) -> int:
        head = 0
        tail = 0
        # Determine whether it is a boundary
        if len(s) < 2:
            return len(s)
        # Two pointers stay at the position of the first element with an initial length of 1
        res = 1
        while tail < len(s) - 1:
            tail += 1
            if s[tail] not in s[head:tail]:
                res = max(tail-head + 1,res)
            else:
                while s[tail] in s[head:tail]:
                    head += 1
        return res

Idea two (hash table)

  • tail pointer moves toward the end;
  • If the element pointed to by the tail pointer exists in the hash table:
    • The head pointer jumps to the left bit of the repeating character;
  • Update hash table and window length.

Code

class Solution:
    def lengthOfLongestSubstring(self, s: str) -> int:
        n = len(s)
        hashmap = {}
        head,res = 0,0
        for tail in range(n):
            # If the tail pointer is in a hash table, jump the head pointer to the previous position on the starting repeating element
            if s[tail] in hashmap:
                head = max(hashmap[s[tail]],head)
            # Update Hash Table
            hashmap[s[tail]] = tail +1
            # Update Length
            res = max(res,tail-head+1)
        return res

C++

  • r The pointer moves toward the end;
  • If the element pointed to by the tail pointer exists in the hash table:
    • l The pointer jumps to the left bit of the repeating character;
  • Update the hash table and window length (return the maximum value at any time).

Code

class Solution {
public:
    int lengthOfLongestSubstring(string s) {
        map<char,int> m;
        int ret = 0,l = 0, r=0;
        while(r<s.size()){
          	//Judging boundaries
            if(m.find(s[r]) != m.end()){
                l = max(l,m[s[r]]+1);
            }
            m[s[r++]] = r;
            ret = max(r-l,ret);
        }
        return ret;
    }
};

C Language

thinking

sliding window

Code

int lengthOfLongestSubstring(char* s){
    int count[95]; // There are 95 printable characters in ASCII, recording the characters encountered while traversing s
    memset(count, 0, 95 * sizeof(int)); // Set all count values to zero
    int max_lenght = 0; // Maximum length of substring without duplicate characters
    int temp = 0; // Stores the length of the substring without duplicate characters found when traversing s
    int p1 = 0, p2 = 0;
    while(s[p1] != '\0' && s[p2] != '\0'){

        if(count[s[p2] - ' '] == 0){ // No duplicate characters encountered
            count[s[p2] - ' '] = 1; // Record characters encountered
            p2 += 1;
            temp = p2 - p1;
        }
        else{ // Duplicate character encountered
            temp = p2 - p1;
            count[s[p1] - ' '] = 0; // Delete records for p1 position characters
            p1 += 1; // p1 right shift
        }

        if(temp > max_lenght){
            max_lenght = temp;
        }
    }
    return max_lenght;
}

Thank

leetcode

And a hard-working self

Topics: Programming Python ascii C Go