fork download
  1. #include <bits/stdc++.h>
  2. using namespace std;
  3.  
  4. int main() {
  5. // your code goes here
  6. string a;
  7. cin>>a; //string consisting of only a and b
  8. int totalA=0;
  9. int totalB=0;
  10. int n=a.size();
  11. for(int i=0;i<n;i++){
  12. if(a[i]=='a'){
  13. totalA++;
  14. }
  15. else{
  16. totalB++;
  17. }
  18. }
  19. int mini=1e9;
  20. for(int i=0;i<n;i++){
  21. int countA=0;
  22. int countB=0;
  23. for(int j=i;j<n;j++){
  24. if(a[j]=='a'){
  25. countA++;
  26. }
  27. else{
  28. countB++;
  29. }
  30. int Ca=totalA-countA; //total count of a after removing from substring
  31. int Cb=totalB-countB;
  32. if(Ca==Cb){
  33. int len=j-i+1;
  34. mini=min(mini,len);
  35.  
  36. }
  37. }
  38. }
  39. cout<<"The minimum substring containing equal number of a and b is:"<<mini;
  40.  
  41. return 0;
  42. }
Success #stdin #stdout 0s 5320KB
stdin
4
aabb
stdout
The minimum substring containing equal number of a and b is:1