Syntax error Program to find possible number of palindromes we can make by trimming string in Python

Program to find possible number of palindromes we can make by trimming string in Python



Suppose we have a string s, we have to find the number of ways we can obtain a palindrome by trimming the left and right sides of s.

So, if the input is like s = "momo", then the output will be 6, as You can get ["mom", "omo", "o", "o", "m", "m", "o")

To solve this, we will follow these steps −

  • Define a function expand() . This will take i, j, s

  • c := 0

  • while i >= 0 and j < size of s and s[i] is same as s[j], do

    • i := i − 1, j := j + 1

    • c := c + 1

  • return c

  • From the main method, do the following

  • c := 0

  • for i in range 0 to size of s, do

    • c := c + expand(i, i, s)

    • c := c + expand(i, i + 1, s)

  • return c

Let us see the following implementation to get better understanding −

Example

 Live Demo

def expand(i, j, s):
   c = 0
   while i >= 0 and j < len(s) and s[i] == s[j]:
      i −= 1
      j += 1
      c += 1
   return c
class Solution:
   def solve(self, s):
      c = 0
      for i in range(len(s)):
         c += expand(i, i, s)
         c += expand(i, i + 1, s)
      return c
ob = Solution()
s = "momo"
print(ob.solve(s))

Input

"momo"

Output

6
Updated on: 2020-10-21T12:18:07+05:30

216 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements