Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
Program to split two strings to make palindrome using Python
Suppose we have two strings a and b whose length are same. We have to select an index and split both strings at that selected index, splitting a into two strings: a_pref and a_suff where a = a_pref | a_suff, and splitting b into two strings: b_pref | b_suff (| is concatenation operator) where b = b_pref + b_suff. Check if a_pref + b_suff or b_pref + a_suff forms a palindrome or not. (Any split may be an empty string)
So, if the input is like a = "pqrst" b = "turqp", then the output will be True because we can split a like ["pq", "rst"] and b like ["tu", "rqp"], so if we join a_pref with b_suff, we will get "pqrqp" which is a palindrome.
To solve this, we will follow these steps −
-
for each pair (x, y) from list of pairs [(a, b), (b, a)], do
i := 0, j := size of x - 1
-
while x[i] is same as y[j] and i 0, do
i := i + 1
j := j - 1
midx := substring of x from index i to j
midy := substring of y from index i to j
-
if midx is palindrome or midy is palindrome, then
return True
return False
Example
Let us see the following implementation to get better understanding −
def solve(a, b): for x, y in [[a, b], [b, a]]: i, j = 0, len(x) - 1 while x[i] == y[j] and i0: i += 1 j -= 1 midx = x[i:j+1] midy = y[i:j+1] if (midx == midx[::-1] or midy== midy[::-1]): return True return False a = "pqrst" b = "turqp" print(solve(a, b))
Input
"pqrst", "turqp"
Output
True
