• Source
    1. #include<bits/stdc++.h>
    2.  
    3. using namespace std;
    4.  
    5. class Solution {
    6. public:
    7. int topKFrequent(string s,int k) {
    8. int left,right,cnt,ans;
    9. char prev;
    10. left=ans=0;
    11. right=1;
    12. unordered_map<char,bool>m;
    13. //prev=s[0];
    14. m[s[0]]=true;
    15. while(right<s.size()) {
    16. if(!m[s[right]]) {
    17. m[s[right]]=true;
    18. }
    19. if(m.size()>k) {
    20. //cout<<right<<endl;
    21. ans=max(ans,right-left);
    22. left=right;
    23. m.erase(m.begin(),m.end());
    24. m[s[left]]=true;
    25. }
    26. //prev=s[right];
    27. right++;
    28. }
    29. ans=max(ans,right-left);
    30. return ans;
    31. }
    32. };
    33. int main()
    34. {
    35. string s;
    36. int k,ans;
    37. cin>>k;
    38. cin>>s;
    39. Solution sol;
    40. ans=sol.topKFrequent(s,k);
    41. cout<<ans<<endl;
    42. }
    43.