
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Check If a String Follows an anbn Pattern 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 input_string[i] is not equal to 'a', then −
- 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
- if input_string[j] is not equal to 'b', then −
- return true
Example (C++)
Let us see the following implementation to get better understanding −
#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
Advertisements