-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtest9.js
More file actions
31 lines (27 loc) · 877 Bytes
/
test9.js
File metadata and controls
31 lines (27 loc) · 877 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
/*
Sliding Window - findLongestSubstring
Write a function called findLongestSubstring, which accepts a string and returns the length of the longest substring with all distinct characters.
findLongestSubstring('') // 0
findLongestSubstring('rithmschool') // 7
findLongestSubstring('thisisawesome') // 6
findLongestSubstring('thecatinthehat') // 7
findLongestSubstring('bbbbbb') // 1
findLongestSubstring('longestsubstring') // 8
findLongestSubstring('thisishowwedoit') // 6
Time Complexity - O(n)
*/
const findLongestSubstring = str => {
let start = 0;
let seen = {};
let longest = 0;
for (i = 0; i < str.length; i++) {
let char = str[i];
if (seen[char]) {
start = Math.max(start, seen[char]);
}
longest = Math.max(longest, i - start + 1);
seen[char] = i + 1;
}
return longest;
};
console.log(findLongestSubstring('longestsubstring'));