
- Python Basic Tutorial
- Python - Home
- Python - Overview
- Python - Environment Setup
- Python - Basic Syntax
- Python - Comments
- Python - Variables
- Python - Data Types
- Python - Operators
- Python - Decision Making
- Python - Loops
- Python - Numbers
- Python - Strings
- Python - Lists
- Python - Tuples
- Python - Dictionary
- Python - Date & Time
- Python - Functions
- Python - Modules
- Python - Files I/O
- Python - Exceptions
Check if a string follows a^n b^n pattern or not in Python
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 s[i] is not same as 'a', then
- 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
- if s[j] is not same as 'b', then
- return True
Let us see the following implementation to get better understanding −
Example
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
- Related Articles
- Check if a string follows anbn pattern or not in C++
- Check if string follows order of characters defined by a pattern or not in Python
- Check if a string is Isogram or not in Python
- Python - Check if a given string is binary string or not
- Check whether N is a Dihedral Prime Number or not in Python
- Python program to check a number n is weird or not
- Python program to check if a string is palindrome or not
- Check if any anagram of a string is palindrome or not in Python
- Python program to check if a given string is Keyword or not
- How to check if two numbers (m,n) are amicable or not using Python?
- How can we check if a JSON object is empty or not in Java?\n
- Check if N is a Factorial Prime in Python
- Program to check regular expression pattern is matching with string or not in Python
- Check if a string represents a hexadecimal number or not
- Check if a king can move a valid move or not when N nights are there in a modified chessboard in Python

Advertisements