Skip to content

Commit bbc3ef9

Browse files
author
jinvicky
committed
characterReplacement solution
1 parent 8373128 commit bbc3ef9

File tree

2 files changed

+54
-0
lines changed

2 files changed

+54
-0
lines changed

longest-common-subsequence/jinvicky.java

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,8 @@
11
class Solution {
2+
// dp 표를 봐야 이해가 더 쉽다. https://twinw.tistory.com/126
3+
// dp, 즉 메모이제이션의 범위는 이전 row인 것이다. (기존 cell 위주의 문제보다 넓은 범위)
24
public int longestCommonSubsequence(String text1, String text2) {
5+
// 왼쪽과 위로 1줄씩 버퍼(여유) 배열이 있다. 즉, dp[0][..], dp[..][0]은 0으로 초기화된 상태
36
int m = text1.length();
47
int n = text2.length();
58

Lines changed: 51 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,51 @@
1+
import java.util.HashMap;
2+
import java.util.Map;
3+
4+
class Solution {
5+
public int characterReplacement(String s, int k) {
6+
Map<Character, Integer> charCount = new HashMap<>();
7+
8+
int left = 0;
9+
int maxFrequency = 0;
10+
int maxLength = 0;
11+
12+
for(int right = 0; right < s.length(); right++) {
13+
char rightChar = s.charAt(right);
14+
15+
charCount.put(rightChar, charCount.getOrDefault(rightChar, 0) + 1);
16+
17+
maxFrequency = Math.max(maxFrequency, charCount.get(rightChar));
18+
19+
if((right - left + 1) - maxFrequency > k) {
20+
char leftChar = s.charAt(left);
21+
22+
charCount.put(leftChar, charCount.get(leftChar) - 1);
23+
left++;
24+
}
25+
26+
maxLength = Math.max(maxLength, right - left + 1);
27+
}
28+
return maxLength;
29+
}
30+
31+
// while문과 배열로 성능이 개선된 풀이
32+
public int characterReplacement2(String s, int k) {
33+
int left = 0, right = 0;
34+
int maxCount = 0, result = 0;
35+
int[] freq = new int[26];
36+
37+
while (right < s.length()) {
38+
freq[s.charAt(right) - 'A']++;
39+
maxCount = Math.max(maxCount, freq[s.charAt(right) - 'A']);
40+
41+
while ((right - left + 1) - maxCount > k) {
42+
freq[s.charAt(left) - 'A']--;
43+
left++;
44+
}
45+
46+
result = Math.max(result, right - left + 1);
47+
right++;
48+
}
49+
return result;
50+
}
51+
}

0 commit comments

Comments
 (0)