您的位置:首页 > 其它

leetcode 123: Palindrome Partitioning II

2013-03-26 08:54 381 查看
Palindrome
Partitioning IIMar
1

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.

class Solution {
public:
int minCut(string s) {
// Start typing your C/C++ solution below
// DO NOT write int main() function
int sz = s.length();
if(sz<1)return 0;

vector<bool> temp(sz, false);
vector<vector<bool>> b(sz, temp);

for(int i=0; i<sz; i++) {
b[i][i] = true;
}

for(int i=0; i<sz-1; i++) {
if(s[i]==s[i+1]) {
b[i][i+1] = true;
}
}

for(int len=3; len<=sz; len++) {
for(int i=0; i<=sz-len; i++) {
int j=i+len-1;
if(s[i]==s[j] && b[i+1][j-1]) {
b[i][j] = true;
}
}
}

vector<int> d(sz, 0);
for(int i=0; i<sz; i++) {
if( b[0][i]) {
d[i]==0;
continue;
}
int min = INT_MAX;
for(int k=1; k<=i; k++) {
if(b[k][i]) {
int x = d[k-1] + 1;
min = min<x ? min : x;
}
}
d[i] = min;
}
return d[sz-1];
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: