Skip to content

Commit b5ab154

Browse files
committed
#243 longest-substring-without-repe... solution
1 parent dce14be commit b5ab154

File tree

1 file changed

+49
-0
lines changed

1 file changed

+49
-0
lines changed
Lines changed: 49 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,49 @@
1+
"""
2+
sliding window 풀이:
3+
알고달레 풀이 참조할 것
4+
start부터 end까지의 부분문자열 길이가 유기적으로 변하면서 이동하여 탐색
5+
s[end]가 set에 존재하지 않으면 s[end] set에 추가하고 ans와 대소비교로 업데이트, end + 1 -> 부분문자열 크기 증가
6+
s[end]가 set에 존재하면 s[start] set에서 제거하고 start + 1 -> s[end]와 같은 문자가 set에 없을 때까지 부분문자열 크기 감소
7+
8+
TC : O(N)
9+
문자열 한번만 순회하고 set의 조회, 추가, 삭제는 O(1)이므로
10+
SC : O(N)
11+
문자열 길이와 set의 크기가 비례
12+
"""
13+
class Solution:
14+
def lengthOfLongestSubstring(self, s: str) -> int:
15+
ans = 0
16+
start, end = 0, 0
17+
chars = set()
18+
while end < len(s) :
19+
if not s[end] in chars :
20+
chars.add(s[end])
21+
ans = max(ans, end - start + 1)
22+
end += 1
23+
else :
24+
chars.remove(s[start])
25+
start += 1
26+
return ans
27+
28+
"""
29+
기존 풀이 :
30+
각 문자를 start로 순회하는 내부에서
31+
새로 추가되는 end 문자와 기존 문자열을 중복검사해서 길이를 늘려나가다가 중복되면 break
32+
33+
TC : O(N^2)
34+
SC : O(N)
35+
36+
class Solution:
37+
def lengthOfLongestSubstring(self, s: str) -> int:
38+
ans = 0
39+
dp = [1] * len(s)
40+
for start in range(len(s)):
41+
chars = set()
42+
for end in range(start, len(s)) :
43+
if not s[end] in chars :
44+
chars.add(s[end])
45+
ans = max(ans, end - start + 1)
46+
else :
47+
break
48+
return ans
49+
"""

0 commit comments

Comments
 (0)