Skip to content

Commit fc55d4e

Browse files
committed
Longest Substring Without Repeating Characters
1 parent df9bd02 commit fc55d4e

File tree

1 file changed

+39
-0
lines changed

1 file changed

+39
-0
lines changed
Lines changed: 39 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,39 @@
1+
/*
2+
Time Complexity: O(n)
3+
Space Complexity: O(c)
4+
(c๋Š” ์‚ฌ์šฉ๋˜๋Š” ๋ชจ๋“  character์˜ ๊ฐ€์ง“์ˆ˜)
5+
6+
solution (two pointers)
7+
8+
begin, end ํฌ์ธํ„ฐ๋ฅผ ๊ฐ๊ฐ 1์— ๋‘๊ณ  ์‹œ์ž‘ํ•œ๋‹ค.
9+
end ํฌ์ธํ„ฐ๋ฅผ 1์”ฉ ์ฆ๊ฐ€ํ•˜๋ฉด์„œ ํƒ์ƒ‰ํ•˜๋‹ค๊ฐ€, ํ˜„์žฌ window ๋‚ด์— ์ด๋ฏธ ์กด์žฌํ•˜๋Š” ๋ฌธ์ž๊ฐ€ ๋˜ ์ถ”๊ฐ€๋œ๋‹ค๋ฉด, ๊ทธ ๋ฌธ์ž๊ฐ€ window์—์„œ ์‚ฌ๋ผ์งˆ ๋•Œ๊นŒ์ง€ begin์„ ์ฆ๊ฐ€์‹œํ‚จ๋‹ค.
10+
11+
(1) end++์„ ํ•˜๋Š” ๋„์ค‘์˜ ๋ชจ๋“  end์— ๋Œ€ํ•ด์„œ๋Š”, ๋˜ ๋‹ค๋ฅธ begin์„ ์ฐพ์„ ํ•„์š”์„ฑ์€ ์—†๋Š”๊ฐ€?
12+
- ํ˜„์žฌ begin๋ณด๋‹ค ๋” ์™ผ์ชฝ์˜ begin : ํ˜„์žฌ์˜ begin์€, window ๋‚ด์— ์ค‘๋ณต ๋ฌธ์ž๊ฐ€ ์—†๊ฒŒ๋” ํ•˜๋Š” leftmost ์ธ๋ฑ์Šค์ด๋‹ค. ๋”ฐ๋ผ์„œ, ๋” ์ž‘์€ begin์€ ์ค‘๋ณต์ด ์žˆ์„ ๊ฒƒ์ด๋ฏ€๋กœ, ํƒ์ƒ‰ํ•  ํ•„์š”๊ฐ€ ์—†๋‹ค.
13+
- ํ˜„์žฌ begin๋ณด๋‹ค ๋” ์˜ค๋ฅธ์ชฝ์˜ begin : ๋” ์งง์€ ๊ธธ์ด๋Š” ํƒ์ƒ‰ํ•  ํ•„์š”๊ฐ€ ์—†๋‹ค.
14+
15+
(2) begin++์„ ํ•˜๋Š” ๋„์ค‘์˜ ๋ชจ๋“  begin์— ๋Œ€ํ•ด์„œ๋Š”, ๋˜ ๋‹ค๋ฅธ end๋ฅผ ์ฐพ์„ ํ•„์š”์„ฑ์€ ์—†๋Š”๊ฐ€?
16+
- ํ˜„์žฌ end๋ณด๋‹ค ๋” ์™ผ์ชฝ์˜ end : ๋” ์งง์€ ๊ธธ์ด๋Š” ํƒ์ƒ‰ํ•  ํ•„์š”๊ฐ€ ์—†๋‹ค.
17+
- ํ˜„์žฌ end๋ณด๋‹ค ๋” ์˜ค๋ฅธ์ชฝ์˜ end : ์ค‘๋ณต๋œ ๋ฌธ์ž๊ฐ€ ์žˆ๋Š” ๊ตฌ๊ฐ„์€ LSWRC๊ฐ€ ๋  ์ˆ˜ ์—†์œผ๋ฏ€๋กœ, ํƒ์ƒ‰ํ•  ํ•„์š”๊ฐ€ ์—†๋‹ค.
18+
*/
19+
class Solution {
20+
public int lengthOfLongestSubstring(String s) {
21+
Set<Character> set = new HashSet<>();
22+
int begin = 0, end = 0;
23+
24+
int ans = 0;
25+
while (end < s.length()) {
26+
if (set.contains(s.charAt(end))) {
27+
while (begin < end && s.charAt(begin) != s.charAt(end)) {
28+
set.remove(s.charAt(begin++));
29+
}
30+
set.remove(s.charAt(begin++));
31+
} else {
32+
set.add(s.charAt(end++));
33+
ans = Math.max(ans, end - begin);
34+
}
35+
}
36+
37+
return ans;
38+
}
39+
}

0 commit comments

Comments
ย (0)