Let's break down the solution steps and see how each step works
We assume we received the following input:
We will create an empty set to store the letters we have encountered and a variable to keep the longest substring we have found.
Now, we will check if the value pointed to by right exists in the set. If it doesn't exist, we will add it to the set and move right one step forward. After that, we will update the longest substring by comparing the size of the set to the value stored in the longSubstr variable.
We will check if the value pointed to by right is in the set. We see that it is not, so we add it to the set and increment right by 1. After that, we take the max between the size of the set and the value in longSubstr.
We check if the value pointed to by right is in the set, meaning c is not in the set. So, we add it to the set, increment right by 1, and check the max substring.
Now, we check if the value pointed to by right, which is a, exists in the set. We see that it does, so we remove it from the set and move left one step forward.
The value pointed to by right is b, and it exists in the set.
Therefore, we move the left pointer one step forward and remove b from the set.
Now we see that b is in the set, so we remove the value pointed to by left and move left one step forward.
The value pointed to by right is c, and it exists in the set.
Therefore, we remove it from the set and move left one step forward.
We will continue with the same technique until step 17 and will get:
function longestSubstring(s) { let left = 0 let right = 0 let maxSubstr = 0 let set = new Set() while (right < s.length) { const currentChar = s[right] if (!set.has(currentChar)) { set.add(currentChar) right++ maxSubstr = Math.max(maxSubstr, right - left) // Update max substring length } else { set.delete(s[left]) left++ } } return maxSubstr } let inputString = 'abcabcbb' console.log(longestSubstring(inputString)) // Output: 3 ("abc")
The above is the detailed content of Longest Substring Without Repeating Characters with Sliding Window Technique. For more information, please follow other related articles on the PHP Chinese website!