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