Skip to content

Commit 6e15e64

Browse files
committed
Add week 7 solutions: longest-substring-without-repeating-characters
1 parent 52823f8 commit 6e15e64

File tree

1 file changed

+26
-0
lines changed

1 file changed

+26
-0
lines changed
Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,26 @@
1+
/**
2+
* https://leetcode.com/problems/longest-substring-without-repeating-characters/
3+
* time complexity : O(n)
4+
* space complexity : O(n)
5+
*/
6+
function lengthOfLongestSubstring(s: string): number {
7+
let n = s.length, ans = 0;
8+
const map = new Map<string, number>();
9+
for (let j = 0, i = 0; j < n; j++) {
10+
if (map.has(s[j])) {
11+
i = Math.max((map.get(s[j]) ?? 0) + 1, i);
12+
}
13+
ans = Math.max(ans, j - i + 1);
14+
map.set(s[j], j);
15+
}
16+
console.log('map:', map);
17+
return ans;
18+
};
19+
20+
const testInput1 = "abcabcbb";
21+
const testInput2 = "bbbbb";
22+
const testInput3 = "pwwkew";
23+
24+
console.log('output1:', lengthOfLongestSubstring(testInput1), 'expected:', 3);
25+
console.log('output2:', lengthOfLongestSubstring(testInput2), 'expected:', 1);
26+
console.log('output3:', lengthOfLongestSubstring(testInput3), 'expected:', 3);

0 commit comments

Comments
 (0)