Skip to content

Commit 07eb9b1

Browse files
longest repeating character replacement solution
1 parent 0f9c2ee commit 07eb9b1

File tree

1 file changed

+31
-0
lines changed

1 file changed

+31
-0
lines changed
Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,31 @@
1+
import java.util.Collections;
2+
import java.util.HashMap;
3+
import java.util.Map;
4+
5+
class Solution {
6+
public int characterReplacement(String s, int k) {
7+
// ํ’€์ด: ์Šฌ๋ผ์ด๋”ฉ ์œˆ๋„์šฐ๋ฅผ ํ™œ์šฉํ•ด ๋ถ€๋ถ„ ๋ฌธ์ž์—ด์„ ๊ตฌํ•œ๋‹ค
8+
// ์ข…๋ฃŒ ์ธ๋ฑ์Šค๋ฅผ ์ฆ๊ฐ€์‹œํ‚ค๊ณ , ๋ถ€๋ถ„ ๋ฌธ์ž์—ด ๊ธธ์ด์—์„œ ๊ฐ€์žฅ ๋งŽ์ด ๋“ค์–ด์žˆ๋Š” ๋ฌธ์ž์˜ ์ˆ˜๋ฅผ ๋บ€ ๊ฐ’์ด k๋ณด๋‹ค ํฐ์ง€ ๋น„๊ตํ•œ๋‹ค.
9+
// ํฌ๋‹ค๋ฉด, ์‹œ์ž‘ ์ธ๋ฑ์Šค๋ฅผ ์ฆ๊ฐ€์‹œํ‚จ๋‹ค.
10+
// ๋๊นŒ์ง€ ๋ฐ˜๋ณตํ•˜๋ฉด์„œ ์ตœ๋Œ€ ๊ธธ์ด๋ฅผ ์ €์žฅํ–ˆ๋‹ค๊ฐ€ ๋ฐ˜ํ™˜ํ•œ๋‹ค.
11+
// TC: O(N)
12+
// SC: O(N)
13+
var maxLength = 0;
14+
var start = 0;
15+
var end = 0;
16+
Map<Character, Integer> countByChar = new HashMap<>();
17+
18+
while (end < s.length()) {
19+
countByChar.put(s.charAt(end), countByChar.getOrDefault(s.charAt(end), 0) + 1);
20+
21+
while ((end - start + 1 - Collections.max(countByChar.values())) > k) {
22+
countByChar.put(s.charAt(start), countByChar.get(s.charAt(start)) - 1);
23+
start += 1;
24+
}
25+
maxLength = Math.max(end - start + 1, maxLength);
26+
end++;
27+
}
28+
29+
return maxLength;
30+
}
31+
}

0 commit comments

Comments
ย (0)