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.
For example, given s = "aab"
,
Return 1
since the palindrome partitioning ["aa","b"]
could be produced using 1 cut.
再计算将s切割成回文串的需要的最小步数dp(n-1)
dp(i)表示从0到i需要切割的次数,dp(0)即为s的第一个字符,所以dp(0) = 0
for j= 0 to i
if f(j,i-j)==true//即从j开始为回文串
dp(i) = min(dp(i),dp(j-1)+1)
注意这里还要判断j=0时的情况,如果j=0 且f(j,i-j)为true,代表从0到i整个是回文的,所以直接dp(i)=0即可。
最后最小步数就是dp(n-1)
class Solution {
public:
bool** f;
int minCut(string s) {
int n = s.length();
longestPalindrome(s);
return build(s);
}
int build(string s){
int n = s.length();
int *dp = new int[n];
dp[0] = 0;
for(int i=1;i<n;i++)
dp[i] = 10000;
for(int i=1;i<n;i++){
for(int j=0;j<=i;j++){
if(f[j][i-j]){
if(j==0){
dp[i] = 0;
}else{
dp[i] = min(dp[i],dp[j-1]+1);
}
}
}
}
return dp[n-1];
}
void longestPalindrome(string s) {
int n = s.length();
f = new bool*[n];
for(int i=0;i<n;i++){
f[i] = new bool[n-i];
f[i][0] = true;
}
for(int i=n-2;i>=0;i--){
for(int j = 1;j<(n-i);j++){
if(s[i]==s[i+j]){
if(j==1)
f[i][j] = true;
else
f[i][j] = f[i+1][j-2];
}else
f[i][j] = false;
}
}
}
};
ac