Check if a string follows anbn pattern or not in C++


Suppose, we are given a string that is made of only two letters a and b. We have to find out if the string is of the form anbn, or in other words it contains n number of a's followed by n number of b's. If true, we return 1 otherwise 0.

So, if the input is like "aaaaaaaaaaaabbbbbbbbbbbb", then the output will be true.

To solve this, we will follow these steps −

  • length := length of input_string
  • for initialize i := 0, when i < length, update (increase i by 1), do &minus
    • if input_string[i] is not equal to 'a', then −
      • Come out from the loop
  • if i * 2 is not equal to length, then −
    • return false
  • for initialize j := i, when j < length, update (increase j by 1), do −
    • if input_string[j] is not equal to 'b', then −
      • return false
  • return true

Example (C++)

Let us see the following implementation to get better understanding −

 Live Demo

#include <bits/stdc++.h>
using namespace std;
bool solve(string input_string) {
   int length = input_string.length();
   int i;
   for (i = 0; i < length; i++)
      if (input_string[i] != 'a')
         break;
      if (i * 2 != length)
         return false;
      for (int j = i; j < length; j++)
         if (input_string[j] != 'b')
            return false;
   return true;
}
int main() {
   string input_string = "aaaaaaaaaaaabbbbbbbbbbbb";
   cout << solve(input_string)<< endl;
   return 0;
}

Input

"aaaaaaaaaaaabbbbbbbbbbbb"

Output

1

Updated on: 18-Jan-2021

220 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements