Advertisement
Guest User

problem3

a guest
Oct 20th, 2019
101
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.72 KB | None | 0 0
  1. class Solution {
  2. public:
  3.  
  4.     int balancedString(string s) {
  5.         //sliding window
  6.         int n = s.length(),cnt = n/4, ans = n;
  7.         unordered_map<char, int> mp, mp2, count;
  8.         for(char c: s){
  9.             mp[c]++; //get count for each char
  10.         }
  11.         bool found = false;
  12.         for(auto& keyVal: mp){
  13.             if(keyVal.second > cnt){
  14.                 found = true;
  15.                 mp2[keyVal.first] = keyVal.second - cnt; //map2 keeps the excessive amount of char
  16.             }
  17.         }
  18.         if(!found) return 0; //if no excess, return 0
  19.         int start =0;
  20.         //now find the minimum window which has the required number of char
  21.         for(int i=0; i< n; i++){
  22.             char c = s[i];
  23.             count[c]++;
  24.             //increase start here
  25.             while(true){
  26.                 int tmp = start;
  27.                 while(start < n && !mp2.count(s[start])){ //for characters not inside mp2, just skip
  28.                     count[s[start++]]--;
  29.                 }
  30.                 while(start < n && mp2.count(s[start]) && count[s[start]] > mp2[s[start]]){
  31.                     count[s[start++]]--;//if char is inside the mp2 and current count greater than mp2 count, skip
  32.                 }
  33.                 if(tmp == start) break; //if cannot move further, break
  34.             }
  35.  
  36.             //check if solution found
  37.             bool found = true;
  38.             for(auto& keyValue: mp2){
  39.                 if(count[keyValue.first] < keyValue.second){
  40.                     found = false;
  41.                 }
  42.             }
  43.             if(found){
  44.                 ans = min(ans, i - start +1); //if found a solution, get the minimal
  45.             }
  46.         }
  47.         return ans;
  48.     }
  49. };
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement