Skip to content

Commit 5b0fcd3

Browse files
committed
longest substring w/o repeating chars solution
1 parent 78dae2d commit 5b0fcd3

File tree

1 file changed

+31
-0
lines changed

1 file changed

+31
-0
lines changed
Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,31 @@
1+
class Solution:
2+
def lengthOfLongestSubstring(self, s: str) -> int:
3+
"""
4+
๋”•์…”๋„ˆ๋ฆฌ๋ฅผ ์‚ฌ์šฉํ•˜์—ฌ ์ด์ „์— ๋‚˜์™”๋˜ ์ธ๋ฑ์Šค๋ฅผ ๊ธฐ์–ต
5+
์ค‘๋ณต๋˜์ง€ ์•Š์•˜๋‹ค๋ฉด answer๋ฅผ ์ €์žฅํ•ด ๋‚˜๊ฐ
6+
์ค‘๋ณต์ด ๋ฐœ์ƒํ•˜๊ณ  begin๊ณผ end์‚ฌ์ด๋ผ๋ฉด ์ค‘๋ณต ๋ฐœ์ƒ ์›์ธ ๋‹ค์Œ์„ begin์œผ๋กœ ์„ธํŒ… ํ›„ ๋‹ค์‹œ ๊ณ„์‚ฐ
7+
8+
Time Complexity : O(n)
9+
Space Complexity : O(n)
10+
11+
"""
12+
answer, begin, end = 0, 0, 0
13+
hash_map = dict()
14+
15+
while end < len(s):
16+
ch = s[end]
17+
hash_map[ch] = hash_map.get(ch, -1)
18+
19+
if hash_map[ch] == -1: #ํ•œ ๋ฒˆ๋„ ๋‚˜์˜ค์ง€ ์•Š์•˜๋‹ค.
20+
hash_map[ch] = end
21+
answer = max(answer, end-begin+1)
22+
else:
23+
if begin<=hash_map[ch]<end: #์ค‘๋ณต์ด ์ƒ๊ฒผ๋‹ค.
24+
begin = hash_map[ch]+1
25+
else:
26+
answer = max(answer, end-begin+1)
27+
hash_map[ch] = end
28+
end += 1
29+
30+
return answer
31+

0 commit comments

Comments
ย (0)