- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- MS Excel
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP
- Physics
- Chemistry
- Biology
- Mathematics
- English
- Economics
- Psychology
- Social Studies
- Fashion Studies
- Legal Studies
- 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 number of ways we can split a palindrome in python
Suppose we have a string s, we have to find the number of ways we can partition the string such that each part is a palindrome.
So, if the input is like s = "xyyx", then the output will be 3, as we have splits like: ["x", "yy", "x"], ["x", "y", "y", "x"], ["xyyx"].
To solve this, we will follow these steps:
- n := size of s
- table := a list of size n + 1 and fill it with 0
- table[0] := 1
- for i in range 0 to n, do
- for j in range 0 to i - 1, do
- sub := s[from index j to i]
- if sub is palindrome, then
- table[i] := table[i] + table[j]
- for j in range 0 to i - 1, do
- return last element of table
Let us see the following implementation to get better understanding:
Example
class Solution: def solve(self, s): n = len(s) table = [1] + [0] * n for i in range(n + 1): for j in range(i): sub = s[j:i] if sub == sub[::-1]: table[i] += table[j] return table[-1] ob = Solution() s = "xyyx" print(ob.solve(s))
Input
"xyyx"
Output
3
Advertisements