-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path3.js
38 lines (35 loc) · 1.03 KB
/
3.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
/**
* 3
* https://leetcode.com/problems/longest-substring-without-repeating-characters/
*
* Final thoughts:
* - blank slate problem - determined the solution technique, start writing a boilerplate
* - visualize the first iteration to have before your eyes the condition for changing the behavior of the code
* - to search for repeated characters in a string, use a Set
*/
/**
* @param {string} s
* @return {number}
* time = O(n)
* space = O(n)
*/
var lengthOfLongestSubstring = function(s) {
let left = 0
let right = 0
let maxLen = 0
const set = new Set()
while (right < s.length) {
if (!set.has(s[right])) {
set.add(s[right])
maxLen = maxLen > set.size ? maxLen : set.size
right++
} else {
set.delete(s[left])
left++
}
}
return maxLen
};
console.log(lengthOfLongestSubstring("abcabcbb")) // => 3 ("abc")
console.log(lengthOfLongestSubstring("bbbbb")) // => 1 ("b")
console.log(lengthOfLongestSubstring("pwwkew")) // => 3 ("wke")