Skip to content

Commit 516540e

Browse files
committed
feat: 3. Longest Substring Without Repeating Characters
1 parent 9defd5e commit 516540e

File tree

1 file changed

+30
-0
lines changed

1 file changed

+30
-0
lines changed
Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,30 @@
1+
// n: len(s)
2+
// Time complexity: O(n^2)
3+
// Space complexity: O(n)
4+
5+
/**
6+
* @param {string} s
7+
* @return {number}
8+
*/
9+
var lengthOfLongestSubstring = function (s) {
10+
let answer = 0;
11+
const map = new Map();
12+
13+
for (let i = 0; i < s.length; i++) {
14+
const chr = s[i];
15+
16+
if (map.has(chr)) {
17+
const temp = map.get(chr);
18+
for (const [key, value] of map) {
19+
if (value <= temp) {
20+
map.delete(key);
21+
}
22+
}
23+
}
24+
25+
map.set(chr, i);
26+
answer = Math.max(answer, map.size);
27+
}
28+
29+
return answer;
30+
};

0 commit comments

Comments
 (0)