-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
28 lines (26 loc) · 931 Bytes
/
index.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
/**
* @param {string} string
* @return {number}
*/
const lengthOfLongestSubstring = (string) => {
const map = {};
let from = 0;
return string.split("").reduce((max, char, index) => {
// store the last seen index of this character in 'map'
const lastSeenIndex = map[char];
// check if this character already exists in current window
const windowContainsCharacter = lastSeenIndex >= from;
// update where from the window starts if necessary
from = windowContainsCharacter ? lastSeenIndex + 1 : from;
// store the last seen index of this character in 'map'
map[char] = index;
// get the size of the window, accounting for 0-based indexing
const windowSize = index - from + 1;
// return the biggest window size so far
return Math.max(max, windowSize);
}, 0);
};
// lengthOfLongestSubstring('pwwkew');
/**
* ! Solving this problem using sliding window algorithm !
*/