imashutosh51

Palindromic Partitioning

May 10th, 2026 (edited)
37
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.23 KB | None | 0 0
  1. def isPalindrome(s,i,j,palin):
  2.     if i>=j:
  3.         return True
  4.        
  5.     if palin[i][j]!=-1:
  6.         return palin[i][j]
  7.        
  8.     palin[i][j]=(s[i]==s[j] and isPalindrome(s,i+1,j-1,palin))
  9.    
  10.     return palin[i][j]
  11.  
  12. def fun(s,i,dp,palin):
  13.     # Returning -1 avoids counting an extra cut after the last partition.
  14.     # Example: "aa|b" already used 1 cut.
  15.     # After processing last partition, recursion reaches end of string.
  16.     # If we return 0 here, final answer becomes 2 instead of 1.
  17.     if i>=len(s): #it must need to take a cut(and before cut it should be palindrome) for calling the fun on further so suppose aa is there so for calling after aa, it must consider 1 cut.
  18.         return -1
  19.        
  20.     if dp[i]!=-1:
  21.         return dp[i]
  22.        
  23.     temp=float('inf')
  24.    
  25.     for j in range(i,len(s)):
  26.        
  27.         if isPalindrome(s,i,j,palin):
  28.             temp=min(temp,1+fun(s,j+1,dp,palin))
  29.                
  30.     dp[i]=temp
  31.    
  32.     return dp[i]
  33.  
  34. class Solution:
  35.     def palPartition(self,s):
  36.         n=len(s)
  37.        
  38.         #dp[i] means minimum palindrome cuts needed for s[i:]
  39.         dp=[-1]*n
  40.        
  41.         palin=[[-1]*n for _ in range(n)]
  42.        
  43.         return fun(s,0,dp,palin)
Advertisement
Add Comment
Please, Sign In to add comment