# Check if a string follows a^n b^n pattern or not in Python

PythonServer Side ProgrammingProgramming

Suppose we have a string s we have to check whether the string is following the pattern a^nb^n or not. This is actually a string when n = 3, the string will be "aaabbb".

So, if the input is like s = "aaaaabbbbb", then the output will be True as this follows a^5b^5.

To solve this, we will follow these steps −

• size := size of s
• for i in range 0 to size - 1, do
• if s[i] is not same as 'a', then
• come out from loop
• if i * 2 is not same as size, then
• return False
• for j in range i to size - 1, do
• if s[j] is not same as 'b', then
• return False
• return True

Let us see the following implementation to get better understanding −

## Example

Live Demo

def solve(s):
size = len(s)
for i in range(size):
if s[i] != 'a':
break
if i * 2 != size:
return False
for j in range(i, size):
if s[j] != 'b':
return False
return True
s = "aaaaabbbbb"
print(solve(s))

## Input

"aaaaabbbbb"

## Output

True