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
  • return counter

Example(Python)

Let us see the following implementation to get a better understanding −

 Live Demo

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

Updated on: 29-Apr-2020

4K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements