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.
Subscribe to see which companies asked this question.
此题通过率不高,试过两种方法都失败了,最后参考网友的代码通过,首先介绍自己的代码错在哪里:
class Solution {
public:
int hui(string s){
if(s.empty()) return 0;
int size = s.size();
int flag = 0;
int i = 0;
//cout<<s<<" hui"<<endl;
while(i < size / 2){
if(s[i] != s[size - 1 - i]){
flag = 1;
break;
}
i++;
}
if(flag == 1) return hui(s.erase(size - 1, 1));
if(flag == 0) return size;
}
int minCut(string s) {
if(s.size() == 1) return 0;
int k;
int i = 0,j = 0;
string ss = s;
reverse(ss.begin(),ss.end());
while(!s.empty()){
k = Solution::hui(s);
i++;//cout<< s << ' ' << k<<endl;
s.erase(0, k);
}
while(!ss.empty()){
k = Solution::hui(ss);
j++;//cout<< s << ' ' << k<<endl;
ss.erase(0, k);
}
if(i < j)
return i - 1;
else
return j - 1;
}
};
开始想的是分别正序反序从第一个字母匹配最长的字符串并且递归,提交后短点的字符串都通过了,一个答案为273次分割的字符串算出281次才明白递归分类错误,之后尝试,依次从中间截断,因为子串依然采用类似贪心算法的方法,最大匹配回文,导致结果为277,依旧不通过。
正确答案如下:
class Solution {
public:
int minCut(string s) {
const int N = s.size();
if(N<=1) return 0;
int i, j, minCUTS[N+1];
for(i=0; i<=N; ++i) minCUTS[i] = i-1;
for(i=1;i<N;i++)
{
for(j=0;(i-j)>=0 && (i+j)<N && s[i-j]== s[i+j]; ++j) // odd-length substrings
minCUTS[i+j+1] = min(minCUTS[i+j+1], 1 + minCUTS[i-j]);
for(j=0;(i-j-1)>=0 && (i+j)<N && s[i-j-1]== s[i+j]; ++j) // even-length substrings
minCUTS[i+j+1] = min(minCUTS[i+j+1], 1 + minCUTS[i-j-1]);
}
return minCUTS[N];
}
};
看懂后发现该算法的确很巧妙,首先没有采用递归,设置数组minCUTS,对应i下标表示前i个数组中最小分割数;
之后大循环为起点i,分别进行两种回文匹配:奇数与偶数;
巧妙之处就在于,在达到最大分割之前每次取到回文串与前面的串即已经求出的最小分割次数求和并刷新所在字符串最小分割次数;
看似复杂的问题,被简单化,且运算效率变高