 
  Data Structure Data Structure
 Networking Networking
 RDBMS RDBMS
 Operating System Operating System
 Java Java
 MS Excel MS Excel
 iOS iOS
 HTML HTML
 CSS CSS
 Android Android
 Python Python
 C Programming C Programming
 C++ C++
 C# C#
 MongoDB MongoDB
 MySQL MySQL
 Javascript Javascript
 PHP 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
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
Advertisements
 