
- 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
Program to count number of palindromic substrings in Python
Suppose we have a string s, we have to find the number of palindromic substrings in s.
So, if the input is like s = "level", then the output will be 7, as the palindromic substrings are: ["l","e","v","e","l","eve","level"]
To solve this, we will follow these steps −
- Define a function check_palindrome(). This will take string, left, right
- ans := 0
- while left >= 0 and right < size of s, do
- if s[left] is same as s[right], then
- ans := ans + 1
- left := left - 1
- right := right + 1
- otherwise,
- return ans
- if s[left] is same as s[right], then
- return ans
- From the main method, do the following −
- ans := 0
- for char_index in range 0 to size of s, do
- ans := ans + check_palindrome(s, char_index - 1, char_index + 1)
- ans := ans + check_palindrome(s, char_index, char_index + 1)
- return (ans) + size of s
Let us see the following implementation to get better understanding −
Example
class Solution: def solve(self, s): def check_palindrome(string, left, right): ans = 0 while left >= 0 and right < len(s): if s[left] == s[right]: ans += 1 left -= 1 right += 1 else: return ans return ans ans = 0 for char_index in range(len(s)): ans += check_palindrome(s, char_index - 1, char_index + 1) ans += check_palindrome(s, char_index, char_index + 1) return (ans) + len(s) ob = Solution() print(ob.solve("level"))
Input
"level"
Output
7
- Related Articles
- Program to count number of homogenous substrings in Python
- Palindromic Substrings in Python
- Program to count number of distinct substrings in s in Python
- Count all Prime Length Palindromic Substrings in C++
- Count of Palindromic substrings in an Index range in C++
- Program to count number of similar substrings for each query in Python
- Program to check whether all palindromic substrings are of odd length or not in Python
- Rearrange the string to maximize the number of palindromic substrings in C++
- Program to count maximum score from removing substrings in Python
- Program to count substrings that differ by one character in Python
- Program to find maximum number of non-overlapping substrings in Python
- Program to count substrings with all 1s in binary string in Python
- Program to find number of substrings with only 1s using Python
- Program to find out the number of pairs of equal substrings in Python
- C++ code to count number of even substrings of numeric string

Advertisements