fork download
  1. #include <bits/stdc++.h>
  2. using namespace std;
  3.  
  4. int main()
  5. {
  6. int n;
  7. cin>>n;
  8.  
  9. string s;
  10. cin>>s;
  11.  
  12. int k;
  13. cin>>k;
  14.  
  15. int i=0; // Left pointer
  16. int count = 0;
  17. // store each character and its frequency in the map
  18. unordered_map<char,int>mp;
  19. for(int j=0; j<n; j++) // 'j' Right pointer
  20. {
  21. mp[s[j]] = mp[s[j]] + 1; // increment the current character and store its frequency in map
  22.  
  23. // If the distint charcter i mean greater than 'k'
  24. //shrink the window from left
  25. while(mp.size()>=k) // mp.size() means entire string chi frequency
  26. {
  27. mp[s[i]] = mp[s[i]] - 1; // remove that element
  28.  
  29. // Remove the character from the map
  30. // if its frequency becomes zero
  31. if(mp[s[i]]==0)
  32. {
  33. mp.erase(s[i]);
  34. }
  35.  
  36. count = count + (n-j); // then count the substrings
  37. i++; // move the left pointer ahead
  38. }
  39. }
  40. cout<<count;
  41. }
Success #stdin #stdout 0s 5324KB
stdin
5
abcca
3
stdout
4