-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathlengthOfLongestSubstring.js
More file actions
36 lines (34 loc) · 901 Bytes
/
lengthOfLongestSubstring.js
File metadata and controls
36 lines (34 loc) · 901 Bytes
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
// Given a string s, find the length of the longest substring without repeating characters.
// var lengthOfLongestSubstring = function (s) {
// let max_len = 0;
// let curr = 0;
// let hash = {};
// if (s.length < 2) {
// return s.length;
// }
// for (let i = 0; i < s.length; i++) {
// if (hash[s[i]] == null) {
// curr += 1;
// } else {
// curr = Math.min(i - hash[s[i]], curr + 1);
// }
// console.log(hash);
// max_len = Math.max(max_len, curr);
// hash[s[i]] = i; //save the index
// }
// return max_len;
// };
var lengthOfLongestSubstring = function (s) {
let win = [];
let len = 0;
for (const val of Array.from(s)) {
if (!win.includes(val)) {
win.push(val);
len = Math.max(len, win.length);
} else {
win.splice(0, win.findIndex((cur) => cur === val) + 1);
win.push(val);
}
}
return len;
};