132. Palindrome Partitioning II
Problem
Return the minimum number of cuts needed to split s into pieces that are all palindromes.
Example: "aab" → 1 ("aa" | "b"); "a" → 0
Constraints: length ≤ 2000.
cuts[i] = min cuts for s[:i]. Expand around every centre; each palindrome s[l..r] gives cuts[r+1] = min(cuts[r+1], cuts[l] + 1). Base cuts[0] = −1.
Complexity: O(n²) time, O(n) space.
class Solution:
def minCut(self, s: str) -> int:
n = len(s)
cuts = [i - 1 for i in range(n + 1)] # worst case: cut between every char
for c in range(n):
for l, r in ((c, c), (c, c + 1)):
while l >= 0 and r < n and s[l] == s[r]:
cuts[r + 1] = min(cuts[r + 1], cuts[l] + 1)
l, r = l - 1, r + 1
return cuts[n]
assert Solution().minCut("aab") == 1
assert Solution().minCut("a") == 0
assert Solution().minCut("abccbc") == 2
class Solution {
public int minCut(String s) {
int n = s.length();
int[] cuts = new int[n + 1];
for (int i = 0; i <= n; i++) cuts[i] = i - 1;
for (int c = 0; c < n; c++)
for (int[] lr : new int[][]{{c, c}, {c, c + 1}})
for (int l = lr[0], r = lr[1]; l >= 0 && r < n && s.charAt(l) == s.charAt(r); l--, r++)
cuts[r + 1] = Math.min(cuts[r + 1], cuts[l] + 1);
return cuts[n];
}
}
func minCut(s string) int {
n := len(s)
cuts := make([]int, n+1) // cuts[i] = min cuts for s[:i]; cuts[0] = -1
for i := range cuts {
cuts[i] = i - 1 // worst case: cut between every character
}
for c := 0; c < n; c++ {
for _, lr := range [][2]int{{c, c}, {c, c + 1}} { // odd and even palindromes centred at c
l, r := lr[0], lr[1]
for l >= 0 && r < n && s[l] == s[r] {
cuts[r+1] = min(cuts[r+1], cuts[l]+1)
l, r = l-1, r+1
}
}
}
return cuts[n]
}