您的位置:首页 > 其它

Palindrome Partitioning II(找给定字符串分割次数获取回文字串, 动态规划)

2013-07-23 01:21 411 查看
/***
Palindrome Partitioning IIMar 19518 / 34344
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.

题目大意:给出一个字符串,求出最小分割次数,使得分割出来的字符串是回文

思路:动态规划。从后面开始往前遍历,从字串起点i开始到j的字串为回文,那么
就分为两种情况:1、i-j为一段  2、i-j不为一段,两种情况取分割较少的为
dp[i] = min(dp[i], dp[j+1] + 1)
*/

#include <iostream>
#include <stdlib.h>
#include <string>
using namespace std;

int minCut(string s) {
// Start typing your C/C++ solution below
// DO NOT write int main() function
int   length = s.size();
int dp[length+1];
bool isPalin[length][length];

//首先初始化dp数组,长度为length时,最小分割次数为0,长度为0时,分割次数为length-1
for(int i=0; i<=length; i++)
dp[i] = length - i;

//isPalin[i][j] 表示从i到j之间的子串是否回文
for(int i=0; i<length; i++)
for(int j=0; j<length; j++)
isPalin[i][j] = false;

for(int i=length-1; i>=0; i--){
for(int j=i; j<length; j++){
//如果子串i-j的头尾相同,如果此时子串长度为2或除掉头尾i和j的字串也是回文,那么该i-j的串也是回文
if(s[i] == s[j] && (j - i <= 1 || isPalin[i+1][j-1])){
isPalin[i][j] = true;
dp[i] = min(dp[i], dp[j+1] + 1);  //比较当前回文串i-j与i-j之后的j起始点比较,取小的一个
}
}
}

return dp[0]-1;
}
int main()
{
string s ;
cin >> s;
cout << minCut(s) << endl;

system("pause");
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: