Program to check a string can be split into three palindromes or not in Python

PythonServer Side ProgrammingProgramming

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
raja
Published on 07-Oct-2021 09:22:02
Advertisements