- 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
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
To Continue Learning Please Login
Login with Google