回文的最小分割数
1.minCut[i]表示从0到i最少回文切割数
2.dp[j][i]=true表示str[j..i]是回文
3.dp[j][i] = (s[i] == s[j] && (i - j < 2 || dp[j + 1][i - 1]))
4.minCut[i+1] = min(minCut[i+1], minCut[j] + 1);(j=< i < len) 当str[j..i]是回文子串时
整体思路,从前到后遍历整个字符串求从0到每一个字符串i的最少回文切割数。
求0~i是否为回文子串时,从后往前遍历,求i-1 ~ i, i- 2 ~ i……的最少回文切割数。
#include <vector>
#include <iostream>
#include <sstream>
using namespace std;
int fun(string s) {
int n = s.size();
vector<vector<bool>> dp(n, vector<bool>(n, false)); //dp[i][j]表示i-j是否为回文子串
vector<int> minCut(n+1, 0); //minCut[i]表示从0到i最少回文切割数
for (int i = 0; i <= n; i++) //初始化
minCut[i] = i - 1;
for (int i = 1; i < n; i++) {
for (int j = i; j >= 0; j--) {
if (s[i] == s[j] && (i - j < 2 || dp[j + 1][i - 1])) { //判断j-i是否为回文子串
dp[j][i] = true;
minCut[i+1] = min(minCut[i+1], minCut[j] + 1);
}
}
}
return minCut[n];
}
int main(){
string s;
cin >> s;
int a = fun(s);
return 0;
}