DEV Community

Abhishek Chaudhary
Abhishek Chaudhary

Posted on

Palindrome Partitioning II

Given a string s, partition s such that every substring of the partition is a palindrome.

Return the minimum cuts needed for a palindrome partitioning of s.

Example 1:

Input: s = "aab"
Output: 1
Explanation: The palindrome partitioning ["aa","b"] could be produced using 1 cut.

Example 2:

Input: s = "a"
Output: 0

Example 3:

Input: s = "ab"
Output: 1

Constraints:

  • 1 <= s.length <= 2000
  • s consists of lowercase English letters only.

SOLUTION:

class Solution:
    def isPalindrome(self, s, i, j):
        if (i, j) in self.PalCache:
            return self.PalCache[(i, j)]
        val = False
        if i >= j - 1:
            val = s[i] == s[j - 1]
        elif s[i] == s[j - 1]:
            val = self.isPalindrome(s, i + 1, j - 1)
        self.PalCache[(i, j)] = val
        return val

    def mcuts(self, s, i, n):
        if i == n:
            return -1
        if i in self.cache:
            return self.cache[i]
        mincuts = n - i - 1
        for j in range(i + 1, n + 1):
            if self.isPalindrome(s, i, j):
                val = self.mcuts(s, j, n)
                mincuts = min(mincuts, 1 + val)
        self.cache[i] = mincuts
        return mincuts

    def minCut(self, s: str) -> int:
        self.cache = {}
        self.PalCache = {}
        n = len(s)
        return self.mcuts(s, 0, n)
Enter fullscreen mode Exit fullscreen mode

AWS GenAI LIVE image

Real challenges. Real solutions. Real talk.

From technical discussions to philosophical debates, AWS and AWS Partners examine the impact and evolution of gen AI.

Learn more

Top comments (0)

Qodo Takeover

Introducing Qodo Gen 1.0: Transform Your Workflow with Agentic AI

Rather than just generating snippets, our agents understand your entire project context, can make decisions, use tools, and carry out tasks autonomously.

Read full post

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay