Program to check two parts of a string are palindrome or not in Python

Suppose we have two strings S and T of same length, we have to check whether it is possible to cut both strings at a common point so that the first part of S and the second part of T form a palindrome.

So, if the input is like S = "cat" T = "pac", then the output will be True, as If we cut the strings into "c" + "at" and "d" + "ac", then "c" + "ac" is a palindrome.

To solve this, we will follow these steps −

  • n := size of a

  • i := 0

  • while i < n and a[i] is same as b[n-i-1], do

    • i := i + 1

  • return true when a[from index i to n-i-1] is palindrome or b[from index i to n-i-1] is palindrome

Let us see the following implementation to get better understanding −


 Live Demo

class Solution:
   def solve(self, a, b):
      n = len(a)
      i = 0
      while i < n and a[i] == b[-i-1]:
         i += 1
      palindrome = lambda s: s == s[::-1]
      return palindrome(a[i:n-i]) or palindrome(b[i:n-i])
ob = Solution()
S = "cat"
T = "dac"
print(ob.solve(S, T))





Updated on: 07-Oct-2020


Kickstart Your Career

Get certified by completing the course

Get Started