您的位置:首页 > 编程语言 > C语言/C++

LeetCode——Palindrome Partitioning II

2014-05-22 23:03 239 查看


Palindrome Partitioning II

 

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.

思路:这道题的思路可以借鉴Palindrome Partitioning的思路,加以修改。

利用两处dp算法:

1、用来判断从i到j的子串是不是回文串

2、定义状态dp[i],表示字符串s的字串0到i,可以进行的最少分割。则最后dp[len-1]即为所要求的答案。

代码:
class Solution {
public:
vector<vector<int> > vt;
bool dpjudge(string &s, int i, int j) {
if (i > j)
return false;
if (vt[i][j] != -1)
return vt[i][j];
if (i == j)
return vt[i][j] = 1;
if (s[i] != s[j])
return vt[i][j] = 0;
else {
if (i + 1 == j)
return vt[i][j] = 1;
else
return vt[i][j] = dpjudge(s, i + 1, j - 1);
}
}
int minCut(string s) {
int len = s.length();
if (len < 2)
return 0;
vector<int> dp, tmp;
dp.clear(), tmp.clear(), vt.clear();
//初始化dp和vt
for (int i = 0; i < len; i++) {
dp.push_back(0);
tmp.push_back(-1);
}
for (int i = 0; i < len; i++) {
vt.push_back(tmp);
}
for (int i = 1; i < len; i++) {
if (dpjudge(s, 0, i)) {
dp[i] = 0;
continue;
}
int ans = i;
for (int j = 0; j < i; j++) {
if (dpjudge(s, j + 1, i))
ans = min(ans, dp[j] + 1);
else
ans = min(ans, dp[j] + i - j);
}
dp[i] = ans;
}
return dp[len - 1];
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  c++ leetcode