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.
題目分析:給出一個字符串,將該字符串分割,使得每部分都是迴文串,求最小的額切割次數。
假設dp[i][j]表示s[i…j]的最小切割次數,則有
代碼如下:
class Solution {
public:
int minCut(string s) {
int n = s.length();
int dp[n][n];
memset(dp,0,sizeof(dp));
for(int i = 0; i < n - 1; i++)
{
if(s[i] == s[i+1]) dp[i][i+1] = 0;
else dp[i][i+1] = 1;
}
for(int len = 2; len <= n; len++)
{
for(int i = 0; i + len < n; i++)
{
int j = i + len;
dp[i][j] = n;
if(s[i] == s[j] && dp[i+1][j-1] == 0) dp[i][j] = 0;
for(int k = i; k < j; k++)
{
dp[i][j] = min(dp[i][j], dp[i][k] + dp[k+1][j] + 1);
}
}
}
return dp[0][n-1];
}
};
結果,超時了。後來看了大神的代碼,增加了一個數組,只用了O(n^2)的複雜度。
代碼如下:
class Solution {
public:
int minCut(string s) {
int n = s.length();
bool isPal[n][n];
memset(isPal,0,sizeof(isPal));
int cut[n];
for(int j = 0; j < n; j++) {
cut[j] = j;
for(int i = 0; i <= j; i++) {
if(s[i] == s[j] && (j - i <= 1 || isPal[i+1][j-1] == true) ) {
isPal[i][j] = true;
if(i > 0) {
cut[j] = min(cut[j],cut[i-1] + 1);
}
else {
cut[j] = 0;
}
}
}
}
return cut[n-1];
}
};
對於每個cut[j],同樣是將[0…j]分成兩部分,只不過,其中一部分是迴文子串。
這道題和Leetcode 279. Perfect Squares的技巧很相似。