Advertisement
nikunjsoni

395

Apr 17th, 2021
127
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.34 KB | None | 0 0
  1. class Solution {
  2. public:
  3.    
  4.     int getMaxUniqueLetters(string s){
  5.         bool map[26] = {0};
  6.         int unique = 0;
  7.         for(char c: s){
  8.             if(!map[c-'a']){
  9.                 unique++;
  10.                 map[c-'a'] = true;
  11.             }
  12.         }
  13.         return unique;
  14.     }
  15.    
  16.     int longestSubstring(string s, int k) {
  17.         int count[26] = {0};
  18.         int maxUnique = getMaxUniqueLetters(s);
  19.         int ans = 0;
  20.         for(int currUnique=1; currUnique<=maxUnique; currUnique++){
  21.             memset(count, 0, sizeof(count));
  22.             int left=0, right=0, unique=0, countAtLeastK=0;
  23.             while(right<s.length()){
  24.                 if(unique <= currUnique){
  25.                     int c = s[right]-'a';
  26.                     if(count[c] == 0) unique++;
  27.                     count[c]++;
  28.                     if(count[c] == k) countAtLeastK++;
  29.                     right++;
  30.                 }
  31.                 else{
  32.                     int c = s[left]-'a';
  33.                     if(count[c] == k) countAtLeastK--;
  34.                     count[c]--;
  35.                     if(count[c] == 0) unique--;
  36.                     left++;
  37.                 }
  38.                 if(unique == currUnique && countAtLeastK == currUnique)
  39.                     ans = max(ans, right-left);
  40.             }
  41.         }
  42.         return ans;
  43.     }
  44. };
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement