【leetcode】Palindrome Partitioning II(hard) ☆
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.
最少切几刀,才能让一个字符串的每个部分都是回文。
思路:
用cut[i] 存储从s[0] ~ s[i - 1] 的子字符串,最短切几刀。
为了方便令 cut[0] = -1
只有一个字符时不需要切刀 cut[1] = 0
其他情况下,依次假设从(-1 ~ i - 2)处切刀,如果 s切刀的后半部分是一个回文, cut[i] = cut[j] + 1; cut[i]取所有切法中数值最小的那个
代码如下:这是O(n3)方法,结果超时了....
class Solution { public: int minCut(string s) { vector<int> cut(s.length() + 1, 0); cut[0] = -1; for(int i = 2; i <= s.length(); i++) { int minNum = s.length(); for(int j = 0; j < i; j++) { if(isPalindrome(s.substr(j, i - j))) { int num = cut[j] + 1; minNum = min(num, minNum); } } cut[i] = minNum; } return cut[s.length()]; } bool isPalindrome(string s) { int i = 0, j = s.length() - 1; while(i < j) { if(s[i] != s[j]) return false; i++; j--; } return true; } };
各种截枝都通过不了,只好看别人的思路,原来可以在判断回文这里下工夫,我是每次都自己判断一遍是不是回文,实际上可以将之前求过的回文信息保存下来,方便后面的判断。
O(N2)解法
class Solution { public: int minCut(string s) { vector<int> cut(s.length() + 1, 0); vector<vector<bool>> isPalindrome(s.length() + 1, vector<bool>(s.length() + 1, false)); cut[0] = -1; for(int i = 2; i <= s.length(); i++) { int minNum = s.length(); for(int j = i - 1; j >= 0 ; j--) { if((s[j] == s[i-1]) && (i - 1 - j < 2 || isPalindrome[j + 1][i - 2])) { isPalindrome[j][i - 1] = true; minNum = min(cut[j] + 1, minNum); } } cut[i] = minNum; } return cut[s.length()]; } };
还有更厉害的,上面的方法保存了判断回文的信息,这有一个不需要保存的,速度非常快
class Solution { public: int minCut(string s) { int n = s.size(); vector<int> cut(n+1, 0); // number of cuts for the first k characters for (int i = 0; i <= n; i++) cut[i] = i-1; for (int i = 0; i < n; i++) { for (int j = 0; i-j >= 0 && i+j < n && s[i-j]==s[i+j] ; j++) // odd length palindrome cut[i+j+1] = min(cut[i+j+1],1+cut[i-j]); for (int j = 1; i-j+1 >= 0 && i+j < n && s[i-j+1] == s[i+j]; j++) // even length palindrome cut[i+j+1] = min(cut[i+j+1],1+cut[i-j+1]); } return cut[n]; } };