File tree Expand file tree Collapse file tree 1 file changed +50
-0
lines changed
longest-repeating-character-replacement Expand file tree Collapse file tree 1 file changed +50
-0
lines changed Original file line number Diff line number Diff line change
1
+ /*
2
+ Time Complexity: O(n)
3
+ Space Complexity: O(1)
4
+
5
+ 투 포인터 방식으로 접근했습니다.
6
+ 현재 상태에서, 두 포인터 사이의 가장 많은 문자를 제외한 나머지 문자의 개수가 k개 이하면 right를 오른쪽으로 1칸,
7
+ k개 초과면 left를 오른쪽으로 1칸씩 이동합니다.
8
+
9
+ 다만, 개인적으로 에너지가 고갈된 상태에서 풀다보니,
10
+ 현재 상태에서 가장 많은 문자를 카운트하는 방식을 counts[26] 배열을 순회하는 식으로 단순하게 짰습니다.
11
+ PQ를 사용하면 조금 더 시간이 개선될 것 같습니다.
12
+ */
13
+ class Solution {
14
+ public int characterReplacement (String s , int k ) {
15
+ int [] counts = new int [26 ];
16
+
17
+ int l = 0 ;
18
+ int r = 0 ;
19
+ int mostCount = 1 ;
20
+
21
+ counts [s .charAt (0 ) - 'A' ] = 1 ;
22
+ int ans = 0 ;
23
+
24
+ while (r < s .length ()) {
25
+ mostCount = 0 ;
26
+ for (int i = 0 ; i < 26 ; i ++) {
27
+ if (counts [i ] > mostCount ) {
28
+ mostCount = counts [i ];
29
+ }
30
+ }
31
+
32
+ if (r - l + 1 - mostCount <= k ) {
33
+ if (r - l + 1 > ans ) {
34
+ ans = r - l + 1 ;
35
+ }
36
+
37
+ r ++;
38
+ if (r == s .length ()) {
39
+ break ;
40
+ }
41
+ counts [s .charAt (r ) - 'A' ]++;
42
+ } else {
43
+ counts [s .charAt (l ) - 'A' ]--;
44
+ l ++;
45
+ }
46
+ }
47
+
48
+ return ans ;
49
+ }
50
+ }
You can’t perform that action at this time.
0 commit comments