|
| 1 | +// Time Complexity: O(n), n: s.length() |
| 2 | +// Space Complexity: O(1) |
| 3 | +class Solution { |
| 4 | + public int characterReplacement(String s, int k) { |
| 5 | + int[] charFreqArr = new int[26]; // s consists of only uppercase English letters |
| 6 | + int maxFreq = 0; |
| 7 | + int maxLength = 0; |
| 8 | + |
| 9 | + for (int left = 0, right = 0; right < s.length(); right++) { |
| 10 | + char letter = s.charAt(right); |
| 11 | + int letterIdx = letter-'A'; |
| 12 | + |
| 13 | + charFreqArr[letterIdx]++; |
| 14 | + maxFreq = Math.max(maxFreq, charFreqArr[letterIdx]); |
| 15 | + |
| 16 | + // when left idx moves rightward? -> k + maxFreq < size of sliding window |
| 17 | + // here, we don't neet to recalculate maxFreq because the point is to calculate 'best' maxFreq |
| 18 | + if (maxFreq + k < right-left+1) { |
| 19 | + char leftChar = s.charAt(left); |
| 20 | + charFreqArr[leftChar-'A']--; |
| 21 | + left++; |
| 22 | + } |
| 23 | + |
| 24 | + maxLength = Math.max(maxLength, right-left+1); |
| 25 | + } |
| 26 | + |
| 27 | + return maxLength; |
| 28 | + } |
| 29 | +} |
| 30 | + |
| 31 | +// AABABBA, k=1, maxFreq=1, maxLength=1 |
| 32 | +// l |
| 33 | +// r |
| 34 | + |
| 35 | +// AABABBA, k=1, maxFreq=2, maxLength=2 |
| 36 | +// lr |
| 37 | + |
| 38 | +// AABABBA, k=1, maxFreq=2, maxLength=3 |
| 39 | +// l r |
| 40 | + |
| 41 | +// AABABBA, k=1, maxFreq=3, maxLength=4 |
| 42 | +// l r |
| 43 | + |
| 44 | +// AABABBA, k=1, maxFreq=3, maxLength=4 ==> fail |
| 45 | +// l r |
| 46 | + |
| 47 | +// AABABBA, k=1, maxFreq=3 |
| 48 | +// l r |
0 commit comments