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.
这题卡时间卡的很严,自认为N^2的算法还是超时
1.
class Solution {
public:
int minCut(string s) {
int l = s.length();
if(l <= 1) return 0;
P = vector<vector<bool> > (l, vector<bool> (l, false));
for(int i = 0; i < l; ++i){
P[i][i] = true;
if(i + 1 < l){
P[i][i + 1] = (s[i] == s[i + 1]);
}
}
for(int k = 2; k < l; ++k)
for(int i = 0; i + k < l; ++i) {
P[i][i + k] = (s[i] == s[i + k]) && P[i + 1][i + k -1];
}
vector<int> F(l, l - 1);
F[0] = 0;
for(int i = 1; i < l; ++i){
if(P[0][i]){
F[i] = 0;
continue;
}
for(int j = 1; j <= i; ++j){
if(P[j][i]){
F[i] = min(F[i], F[j - 1] + 1);
}
}
}
return F[l - 1];
}
private:
vector<vector<bool> > P;
};
2.可以离散化成每一个回文词判断一次,就过了
class Solution {
public:
int minCut(string s) {
int l = s.length();
if(l <= 1) return 0;
P = vector<vector<bool> > (l, vector<bool> (l, false));
vector<int> F(l, 0);
for(int i = 0; i < l; ++i){
F[i] = i;
}
for(int i = 0; i < l; ++i){
for(int j = i; j >= 0; --j){
if(s[i] == s[j] && (i - j < 2 || P[j + 1][i - 1])){
P[j][i] = true;
F[i] = min(F[i], j == 0 ? 0 : F[j - 1] + 1);
}
}
}
return F[l - 1];
}
private:
vector<vector<bool> > P;
};