Skip to content

Commit 6570759

Browse files
committed
Solution: Longest Substring without Repeating Characters
1 parent 4efd6ac commit 6570759

File tree

1 file changed

+42
-0
lines changed
  • longest-substring-without-repeating-characters

1 file changed

+42
-0
lines changed
Lines changed: 42 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,42 @@
1+
/**
2+
* 풀이
3+
* - 주어진 문자열 `s`를 한 번 조회합니다
4+
* - lookup이라는 해시맵 객체를 이용하여 현재 조회하고 있는
5+
* substring에 반복되는 문자가 있는지 검사합니다
6+
*
7+
* Big O
8+
* - N: 주어진 문자열 `s`의 길이
9+
*
10+
* - Time complexity: O(N)
11+
* - Space complexity: O(N)
12+
*/
13+
14+
class Solution {
15+
public:
16+
int lengthOfLongestSubstring(string s) {
17+
if (s.size() == 0) return 0;
18+
19+
unordered_map<char, int> lookup;
20+
lookup.insert({s[0], 0});
21+
22+
int res = 1;
23+
24+
int start = 0;
25+
int end = 1;
26+
27+
while (end < s.size()) {
28+
if (lookup.find(s[end]) != lookup.end()
29+
&& lookup[s[end]] >= start) {
30+
start = lookup[s[end]] + 1;
31+
}
32+
33+
lookup[s[end]] = end;
34+
35+
res = max(res, end - start + 1);
36+
37+
++end;
38+
}
39+
40+
return res;
41+
}
42+
};

0 commit comments

Comments
 (0)