File tree Expand file tree Collapse file tree 1 file changed +31
-0
lines changed
longest-repeating-character-replacement Expand file tree Collapse file tree 1 file changed +31
-0
lines changed Original file line number Diff line number Diff line change
1
+ """
2
+ Solution:
3
+ 1) sliding window 활용
4
+ 2) window 에 들어가는 글자들은 counts 라는 hash map 으로 갯수를 세어준다.
5
+ 3) 순회를 하면서 window size 가 counts에서 가장 큰숫자 + k 보다 크면 invalid window 이기에 left 글자 갯수를 빼고 포인터를 이동해준다.
6
+ 4) max_count 는 기존 max 값과 현재 window 사이즈 중 큰 숫자를 셋해준다.
7
+
8
+ Time: O(n) = O(26n)
9
+ Space: O(1) = O(26)
10
+ """
11
+
12
+
13
+ class Solution :
14
+ def characterReplacement (self , s : str , k : int ) -> int :
15
+ counts = defaultdict (int )
16
+ max_count = 0
17
+
18
+ l , r = 0 , 0
19
+ while l <= r and r < len (s ):
20
+ counts [s [r ]] += 1
21
+ window_size = r - l + 1
22
+
23
+ if window_size > max (counts .values ()) + k :
24
+ counts [s [l ]] -= 1
25
+ l += 1
26
+
27
+ window_size = r - l + 1
28
+ max_count = max (window_size , max_count )
29
+ r += 1
30
+
31
+ return max_count
You can’t perform that action at this time.
0 commit comments