
- Python Basic Tutorial
- Python - Home
- Python - Overview
- Python - Environment Setup
- Python - Basic Syntax
- Python - Comments
- Python - Variables
- Python - Data Types
- Python - Operators
- Python - Decision Making
- Python - Loops
- Python - Numbers
- Python - Strings
- Python - Lists
- Python - Tuples
- Python - Dictionary
- Python - Date & Time
- Python - Functions
- Python - Modules
- Python - Files I/O
- Python - Exceptions
Program to check a string can be split into three palindromes or not in Python
Suppose we have a string s. We have to check whether we can split s into three palindromic substring or not.
So, if the input is like s = "levelpopracecar", then the output will be True because we can split it like "level", "pop", "racecar", all are palindromes.
To solve this, we will follow these steps −
n := size of s
dp := a matrix of order n x n and fill with false
for i in range n-1 to 0, decrease by 1, do
for j in range 0 to n - 1, do
if i >= j, then
dp[i, j] := True
otherwise when s[i] is same as s[j], then
dp[i, j] := dp[i+1, j-1]
for i in range 1 to n - 1, do
for j in range i+1 to n - 1, do
if dp[0, i-1] and dp[i, j-1] and dp[j, n-1] all are true, then
return True
return False
Example
Let us see the following implementation to get better understanding
def solve(s): n = len(s) dp = [[False] * n for _ in range(n)] for i in range(n-1, -1, -1): for j in range(n): if i >= j: dp[i][j] = True elif s[i] == s[j]: dp[i][j] = dp[i+1][j-1] for i in range(1, n): for j in range(i+1, n): if dp[0][i-1] and dp[i][j-1] and dp[j][n-1]: return True return False s = "levelpopracecar" print(solve(s))
Input
"levelpopracecar"
Output
True
- Related Articles
- Program to check a string can be broken into given list of words or not in python
- Program to check whether we can make k palindromes from given string characters or not in Python?
- Program to check whether we can split list into consecutive increasing sublists or not in Python
- Check if given string can be split into four distinct strings in Python
- Program to check whether we can split a string into descending consecutive values in Python
- C++ Program to check given candies can be split with equal weights or not
- C++ Program to check string can be reduced to 2022 or not
- Program to check whether final string can be formed using other two strings or not in Python
- Program to check a string is palindrome or not in Python
- Program to check whether one string can be 1-to-1 mapped into another string in Python
- Program to check subarrays can be rearranged from arithmetic sequence or not in Python
- Program to check string contains consecutively descending string or not in Python
- Program to check the string is repeating string or not in Python
- Program to check whether one point can be converted to another or not in Python
- Program to check three consecutive odds are present or not in Python

Advertisements