Skip to content

Commit 8c9defe

Browse files
committed
longest-repeating-character-replacement solution
1 parent f40ebfb commit 8c9defe

1 file changed

Lines changed: 39 additions & 0 deletions

File tree

Lines changed: 39 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,39 @@
1+
class Solution {
2+
public int characterReplacement(String s, int k) {
3+
/**
4+
1.problem: k번 특정 문자를 골라서 바꿀 수 있다. 이때 same letter 로 이루어진 가장 긴 substring 의 길이을 구하라.
5+
2.constraints
6+
- s.length min = 1, max = 10^5
7+
- k.length min = 0, max = s.length
8+
3.solution
9+
- sliding window: time O(n), space O(1)
10+
*/
11+
12+
int[] table = new int[26];
13+
int n = s.length();
14+
int maxFreq = 0;
15+
int maxLen = 0;
16+
int left = 0;
17+
18+
for(int right = 0; right < n; right++) {
19+
//1.right 확장 -> count 증가
20+
int currentChar = s.charAt(right) - 'A';
21+
table[currentChar]++;
22+
23+
//2.maxFreq update
24+
maxFreq = Math.max(maxFreq, table[currentChar]);
25+
26+
//3.조건 깨지면 left 이동하면서 count--
27+
//바꿔야하는 문자 개수가 k 보다 큰 경우
28+
if((right - left + 1 - maxFreq) > k) {
29+
int idx = s.charAt(left) - 'A';
30+
table[idx]--;
31+
left++;
32+
}
33+
34+
//4.maxLen update
35+
maxLen = Math.max(maxLen, right - left + 1);
36+
}
37+
return maxLen;
38+
}
39+
}

0 commit comments

Comments
 (0)