Advertisement
LaLune

LC #424

Apr 15th, 2022
580
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.85 KB | None | 0 0
  1. class Solution {
  2.     public int characterReplacement(String s, int k) {
  3.        
  4.         //map to keep track of elements in the window
  5.         //Keep highest frequency character
  6.         HashMap<Character, Integer> dict = new HashMap<>();
  7.         int bestFreq = 0;
  8.        
  9.         //longest length answer to return <- longest valid window (subarray)
  10.         int ans = 0;
  11.        
  12.         //back window pointer
  13.         int back = 0;
  14.        
  15.         for (int front=0; front<s.length(); front++) {
  16.             //window increment
  17.             char c = s.charAt(front);
  18.             //increment frequency
  19.             dict.put(c, dict.getOrDefault(c, 0) + 1);
  20.            
  21.             int freq = dict.get(c);
  22.             //check for best frequency, this is because the only way to maximize score is
  23.             //having a large window size with a large frequency of recurring characters, therefor
  24.             //having a low amount of characters to swap K times
  25.             // bestFreq = freq > bestFreq ? freq : bestFreq;
  26.             bestFreq = Math.max(bestFreq, freq);
  27.            
  28.             //check window validity
  29.             int windowsize = front - back + 1;
  30.             while (windowsize - bestFreq > k) {
  31.                 //invalid window, too many characters require replacement but not enough Ks
  32.                 //shrink so that the window is valid within k replacelemt constraint
  33.                 //remove character at back
  34.                 dict.put(s.charAt(back), dict.get(s.charAt(back)) - 1);
  35.                 back++;
  36.                 //update the window size
  37.                 windowsize = front - back + 1;
  38.                
  39.             }
  40.             //valid window, check if it is the better solution
  41.             // ans = windowsize > ans ? windowsize : ans;
  42.             ans = Math.max(ans, windowsize);
  43.         }
  44.         return ans;
  45.     }
  46. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement