
- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
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
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
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
- 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 find maximum number of people we can make happy 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 maximum profit we can make by holding and selling profit in Python
- Program to find number of distinct coin sums we can make with coins and quantities in Python?
- Program to find minimum number of operations to make string sorted in Python
- Program to count number of strings we can make using grammar rules in Python
- Program to find maximum number of consecutive values you can make 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
- C++ Program to find number of RBS string we can form bracket sequences
- Program to find maximum number of coins we can get using Python
Advertisements