LeetCode 0132. Palindrome Partitioning II Solution in Java, Python, C++, JavaScript, Go & Rust | Explanation + Code

CoderIndeed
0
0132. Palindrome Partitioning II

Description

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.

Solutions

Solution 1: Dynamic Programming

First, we preprocess the string s to determine whether each substring s[i..j] is a palindrome, and record this in a 2D array g[i][j], where g[i][j] indicates whether the substring s[i..j] is a palindrome.

Next, we define f[i] to represent the minimum number of cuts needed for the substring s[0..i-1]. Initially, f[i] = i.

Next, we consider how to transition the state for f[i]. We can enumerate the previous cut point j. If the substring s[j..i] is a palindrome, then f[i] can be transitioned from f[j]. If j = 0, it means that s[0..i] itself is a palindrome, and no cuts are needed, i.e., f[i] = 0. Therefore, the state transition equation is as follows:

$$ f[i] = \min_{0 \leq j \leq i} \begin{cases} f[j-1] + 1, & \textit{if}\ g[j][i] = \textit{True} \ 0, & \textit{if}\ g[0][i] = \textit{True} \end{cases} $$

The answer is f[n], where n is the length of the string s.

The time complexity is O(n^2), and the space complexity is O(n^2). Here, n is the length of the string s.

PythonJavaC++GoTypeScriptC#
class Solution: def minCut(self, s: str) -> int: n = len(s) g = [[True] * n for _ in range(n)] for i in range(n - 1, -1, -1): for j in range(i + 1, n): g[i][j] = s[i] == s[j] and g[i + 1][j - 1] f = list(range(n)) for i in range(1, n): for j in range(i + 1): if g[j][i]: f[i] = min(f[i], 1 + f[j - 1] if j else 0) return f[-1](code-box)

Post a Comment

0Comments

Post a Comment (0)

#buttons=(Accept !) #days=(20)

Our website uses cookies to enhance your experience. Check Now
Accept !