|
| 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