3. Longest Substring Without Repeating Characters - JS

Description

Given a string, find the length of the longest substring without repeating characters.

Example

1
2
3
4
5
6
7
8
9
10
11
12
13
14
Input: "abcabcbb"
Output: 3
Explanation: The answer is "abc", with the length of 3.


Input: "bbbbb"
Output: 1
Explanation: The answer is "b", with the length of 1.


Input: "pwwkew"
Output: 3
Explanation: 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.

Solution

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
let lengthOfLongestSubstring = function(s) {
let set = new Set();
let l = 0, r = 0, max = 0;

while( r < s.length ){
if( !set.has(s[r]) ){
set.add(s[r]);
max = Math.max(max, r-l+1);
r++;
}else{
while( set.has(s[r]) ) {
set.delete(s[l]);
l++;
}
}
}
return max;
};