Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- def isPalindrome(s,i,j,palin):
- if i>=j:
- return True
- if palin[i][j]!=-1:
- return palin[i][j]
- palin[i][j]=(s[i]==s[j] and isPalindrome(s,i+1,j-1,palin))
- return palin[i][j]
- def fun(s,i,dp,palin):
- # Returning -1 avoids counting an extra cut after the last partition.
- # Example: "aa|b" already used 1 cut.
- # After processing last partition, recursion reaches end of string.
- # If we return 0 here, final answer becomes 2 instead of 1.
- 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.
- return -1
- if dp[i]!=-1:
- return dp[i]
- temp=float('inf')
- for j in range(i,len(s)):
- if isPalindrome(s,i,j,palin):
- temp=min(temp,1+fun(s,j+1,dp,palin))
- dp[i]=temp
- return dp[i]
- class Solution:
- def palPartition(self,s):
- n=len(s)
- #dp[i] means minimum palindrome cuts needed for s[i:]
- dp=[-1]*n
- palin=[[-1]*n for _ in range(n)]
- return fun(s,0,dp,palin)
Advertisement
Add Comment
Please, Sign In to add comment