- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Palindromic Substrings in Python
Suppose we have a string; we have to count how many palindromic substrings present in this string. The substrings with different start indices or end indices are counted as different substrings even they consist of same characters. So if the input is like “aaa”, then the output will be 6 as there are six palindromic substrings like “a”, “a”, “a”, “aa”, “aa”, “aaa”
To solve this, we will follow these steps −
- count := 0
- for i in range 0 to length if string
- for j in range i + 1 to length of string + 1
- temp := substring from index i to j
- if temp is palindrome, then increase count by 1
- for j in range i + 1 to length of string + 1
- return counter
Example(Python)
Let us see the following implementation to get a better understanding −
class Solution: def countSubstrings(self, s): counter = 0 for i in range(len(s)): for j in range(i+1,len(s)+1): temp = s[i:j] if temp == temp[::-1]: counter+=1 return counter ob1 = Solution() print(ob1.countSubstrings("aaaa"))
Input
"aaaa"
Output
10
- Related Articles
- Program to count number of palindromic substrings in Python
- Count all Prime Length Palindromic Substrings in C++
- Count of Palindromic substrings in an Index range in C++
- 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++
- Longest Palindromic Substring in Python
- Python Grouping similar substrings in list
- Remove Substrings in One Iteration in python
- Program to find length of longest palindromic substring in Python
- Program to find lexicographically smallest non-palindromic string in Python
- Program to find length of longest palindromic subsequence in Python
- Find substrings that contain all vowels in Python
- Python Program to Remove Palindromic Elements from a List
- Find the lexicographically largest palindromic Subsequence of a String in Python
- Program to count number of homogenous substrings in Python

Advertisements