How to Find the Longest Substring Without Repeating Characters in JavaScript
Finding the longest substring without repeating characters is a common problem in programming. This problem can be approached with different algorithms, but one of the most efficient methods is the sliding window technique. This article will explain how to solve this problem using JavaScript.
Problem Definition
Given a string, you need to find the length of the longest substring that does not contain repeating characters. For example, for the input string 'abcabcbb', the longest substring without repeating characters is 'abc', which has a length of 3.
Approach
We'll use the sliding window technique with two pointers to keep track of the current substring. A set will help us track the characters in the current window. The basic idea is to expand the window by moving the right pointer and to contract it by moving the left pointer when a repeating character is found.
Algorithm
- Initialize two pointers
leftandrightto 0, and create a setcharSetto store characters. - Expand the window by moving the
rightpointer and adding characters tocharSet. - If a character is repeated (i.e., it is already in
charSet), move theleftpointer to shrink the window until the repeated character is removed. - Keep track of the maximum length of the window throughout the process.
JavaScript Implementation
function lengthOfLongestSubstring(s) {
let left = 0;
let right = 0;
let maxLength = 0;
const charSet = new Set();
while (right < s.length) {
if (!charSet.has(s[right])) {
charSet.add(s[right]);
maxLength = Math.max(maxLength, right - left + 1);
right++;
} else {
charSet.delete(s[left]);
left++;
}
}
return maxLength;
}
// Example usage
const input = 'abcabcbb';
console.log(lengthOfLongestSubstring(input)); // Output: 3
In this implementation:
- The
whileloop iterates through the string with therightpointer. - If the character at
s[right]is not incharSet, it is added, and the length of the current window is checked for the maximum length. - If the character is already in
charSet, theleftpointer is moved to shrink the window until the repeating character is removed. - Finally,
maxLengthholds the length of the longest substring without repeating characters.
Conclusion
By using the sliding window technique, you can efficiently find the length of the longest substring without repeating characters in a given string. This approach ensures that you only traverse the string once, resulting in a time complexity of O(n). With this method, you can handle large inputs effectively and solve the problem with optimal performance.
Comments
Post a Comment