
- 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
Longest Chunked Palindrome Decomposition in python
Suppose we have a text. We have to find the largest possible k such that there exists a[1], a[2], ..., a[k] such that: Each a[i] is a non-empty string; Their concatenation a[1] + a[2] + ... + a[k] is equal to the given text; For all i in range 1 to k, a[i] = a[{k+1 - i}].
So, if the input is like "antaprezatepzapreanta", then the output will be 11, because we can split it like "(a)(nt)(a)(pre)(za)(tpe)(za)(pre)(a)(nt)(a)".
To solve this, we will follow these steps −
start := 0, end := length of text - 1
initialize temp1 and temp2 with empty strings
ans = 1 when length of text is odd, otherwise 0
while start < end, do −
temp1 := temp1 + text[start]
temp2 := text[end] + temp2
if temp1 is same as temp2, then −
set temp1 and temp2 as empty string
ans := ans + 2
start := start + 1
end := end - 1
if text length is even and (temp1 or temp2 is not empty)
ans := ans + 1
return ans
Let us see the following implementation to get better understanding −
Example
class Solution(object): def longestDecomposition(self, text): start = 0 end = len(text)-1 temp1 = "" temp2 = "" ans = 1 if len(text) & 1 else 0 while start<end: temp1+=text[start] temp2 = text[end]+temp2 if temp1 == temp2: temp1 = temp2 = "" ans+=2 start+=1 end-=1 if len(text)%2 == 0 and(temp1 or temp2): ans += 1 return ans ob = Solution() print(ob.longestDecomposition("antaprezatepzapreanta"))
Input
"antaprezatepzapreanta"
Output
11
- Related Articles
- Program to find length of longest chunked palindrome decomposition in Python
- Longest Palindrome in C++
- Find longest palindrome formed by removing or shuffling chars from string in Python
- Print longest palindrome word in a sentence in C Program
- Find the Length of the Longest possible palindrome string JavaScript
- Palindrome Number in Python
- Valid Palindrome in Python
- Find longest palindrome formed by removing or shuffling chars from string in C++
- Palindrome in Python: How to check a number is palindrome?
- Palindrome Linked List in Python
- Return the Cholesky decomposition in Linear Algebra in Python
- Longest Increasing Subsequence in Python
- Longest Palindromic Substring in Python
- Longest Common Prefix in Python
- Longest Valid Parentheses in Python
