Skip to content

Commit 5ed7b79

Browse files
donghyeon95donghyeon95
donghyeon95
authored and
donghyeon95
committed
feat: Longest Repeating Character Replacement #244
1 parent ee5a1ec commit 5ed7b79

File tree

1 file changed

+45
-0
lines changed

1 file changed

+45
-0
lines changed
Lines changed: 45 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,45 @@
1+
import java.util.HashMap;
2+
import java.util.Map;
3+
import java.util.Set;
4+
5+
class Solution {
6+
public int characterReplacement(String s, int k) {
7+
// K개까지는 용인되는 최대 길이를 구해라
8+
// 2 포인터 => 최대 O(2*N) = O(N)
9+
// 용인 되는 길이면 second++, 용인되는 길이가 아니면 first++;
10+
11+
String[] strings = s.split("");
12+
HashMap<String, Integer> strCnt = new HashMap<>();
13+
int result = 0;
14+
int first = 0;
15+
int second = 0;
16+
17+
while(first<s.length()){
18+
strCnt.put(strings[first], strCnt.getOrDefault(strings[first], 0)+1);
19+
System.out.println(" second: " + second + " first: " + first );
20+
if (getOtherCnt(strCnt) <= k) {
21+
result = Math.max(result, first-second+1);
22+
first++;
23+
}
24+
else {
25+
strCnt.put(strings[second], strCnt.getOrDefault(strings[second],1)-1);
26+
strCnt.put(strings[first], strCnt.getOrDefault(strings[first], 0)-1);
27+
second++;
28+
}
29+
}
30+
31+
return result;
32+
}
33+
34+
public int getOtherCnt(HashMap<String, Integer> strCnt) {
35+
int total = 0;
36+
int max = 0;
37+
for (int a: strCnt.values()) {
38+
total += a;
39+
max = Math.max(max, a);
40+
}
41+
return total - max;
42+
}
43+
}
44+
45+

0 commit comments

Comments
 (0)