Skip to content

Commit 58450ac

Browse files
committed
add longest repeating character replacement solution
1 parent 7040eef commit 58450ac

File tree

1 file changed

+35
-0
lines changed

1 file changed

+35
-0
lines changed
Lines changed: 35 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,35 @@
1+
/**
2+
* ๋ฌธ์ž์—ด s์™€ ์ •์ˆ˜ k๊ฐ€ ์ฃผ์–ด์ง„๋‹ค.
3+
* ๋ฌธ์ž์—ด ๋‚ด ์•„๋ฌด ๋ฌธ์ž๋‚˜ ๋Œ€๋ฌธ์ž ์˜๋ฌธ์ž๋กœ ๋ณ€๊ฒฝํ•  ์ˆ˜ ์žˆ์œผ๋ฉฐ ํ•ด๋‹น ์—ฐ์‚ฐ์„ k๋ฒˆ๊นŒ์ง€ ํ•  ์ˆ˜ ์žˆ์„ ๋•Œ,
4+
* ๊ฐ™์€ ๋ฌธ์ž๋ฅผ ํฌํ•จํ•˜๋Š” ๊ฐ€์žฅ ๊ธด ๋ถ€๋ถ„ ์ˆ˜์—ด์„ ๋ฐ˜ํ™˜ํ•˜์„ธ์š”.
5+
*/
6+
class Solution {
7+
8+
// ์‹œ๊ฐ„๋ณต์žก๋„: O(n)
9+
public int characterReplacement(String s, int k) {
10+
11+
int[] chars = new int[26];
12+
int left = 0;
13+
int maxLength = 0;
14+
int maxCnt = 0;
15+
16+
for (int right = 0; right < s.length(); right++) {
17+
int charIdx = s.charAt(right) - 'A';
18+
chars[charIdx]++;
19+
// ํ˜„์žฌ ์œˆ๋„์šฐ ๋‚ด์—์„œ ๊ฐ€์žฅ ๋งŽ์ด ๋“ฑ์žฅํ•˜๋Š” ๋ฌธ์ž์˜ ๊ฐœ์ˆ˜
20+
maxCnt = Math.max(chars[charIdx], maxCnt);
21+
22+
// window size - max cnt > k (window ์‚ฌ์ด์ฆˆ ์กฐ์ •)
23+
while (right - left + 1 - maxCnt > k) {
24+
chars[s.charAt(left) - 'A']--;
25+
left++;
26+
}
27+
28+
maxLength = Math.max(maxLength, right - left + 1);
29+
}
30+
31+
return maxLength;
32+
33+
}
34+
}
35+

0 commit comments

Comments
ย (0)