题目描述:困难
给你一个字符串 s
,请你将 s
分割成一些子串,使每个子串都是回文。
返回符合要求的 最少分割次数 。
解法 动态规划
cut[i]
is the minimum of cut[j - 1] + 1 (j <= i)
, if [j, i]
is palindrome.
If [j, i]
is palindrome, [j + 1, i - 1]
is palindrome, and c[j] == c[i]
.
a b a | c c
j i
j-1 | [j, i] is palindrome
cut(j-1) + 1
Java
class Solution {
public int minCut(String s) {
char[] c = s.toCharArray();
int n = c.length;
int[] cut = new int[n];
boolean[][] pal =new boolean[n][n];
for(int i = 0;i < n;i++){
int min = i;
for(int j=0;j <= i;j++){
if(c[j] == c[i] &&(j+1 > i-1 || pal[j+1][i-1])){
pal[j][i] = true;
min = j==0 ? 0:Math.min(min,cut[j-1] + 1);
}
}
cut[i] = min;
}
return cut[n-1];
}
}
Python
class Solution(object):
def minCut(self, s):
c = list(s)
n = len(c)
cut = [0 for i in range(n)]# 数组采用for循环,不调用numpy
pal = [[False for i in range(n)] for j in range(n)]
for i in range(n):
min_num = i
for j in range(0,i+1):
if(c[j] == c[i] and (j + 1 > i - 1 or pal[j + 1][i - 1])):
pal[j][i] = True
min_num=0 if j==0 else min(min_num,cut[j-1]+1)
cut[i] = min_num
return cut[n - 1]
参考文献
- https://www.bilibili.com/video/BV1NJ411v7k9?from=search&seid=17040759617716118007
- https://leetcode.com/problems/palindrome-partitioning-ii/discuss/42213/Easiest-Java-DP-Solution-(97.36)