- Related Questions & Answers
- Program to find number of ways we can concatenate words to make palindromes in Python
- Program to count number of unique palindromes we can make using string characters in Python
- Program to check whether we can make k palindromes from given string characters or not in Python?
- Program to count number of ways we can make a list of values by splitting numeric string in Python
- Program to find maximum profit we can make by buying and selling stocks in Python?
- Program to find number of distinct coin sums we can make with coins and quantities in Python?
- Program to count number of strings we can make using grammar rules in Python
- Program to find maximum number of coins we can collect in Python
- Program to count number of palindromes of size k can be formed from the given string characters in Python
- Program to find maximum number of coins we can get using Python
- Program to find number of ways we can decode a message in Python
- Program to find number of ways we can split a palindrome in python
- Program to count number of palindromes after minimum number of split of the string in C++
- Program to find minimum number of operations required to make one string substring of other in Python
- Program to find number of ways we can arrange symbols to get target in Python?

- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who

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 −

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))

"momo"

6

Advertisements