Palindrome Partitioning II
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.
这道题很惭愧,想直接在上一道题的代码上改,结果还是重写了。
之前为了方便算回文,插入“#”。但是程序会报内存不足,所以不能用这种扩展方式,只能拿string.size来建dp数组
后面根据数组,用dp继续做cut。cut的时候 cut j = min(cut j , cut i +1 (if dp[i+1][j] == 1)).要注意该推导式不需要dp[0][i] == 1
class Solution { public: int minCut(string s) { vector<vector <int> >dp; int len = s.size(); if(len == 1)return 0; for(int i = 0 ; i < len ;i++) { vector<int> tp(len,0); dp.push_back(tp); } for(int i = 0 ; i < len ; i++) dp[i][i] = 1; for(int i = 0 ; i < len ;i++) { int j = 1; while(i-j>=0 && i+j<len && s[i-j] == s[i+j]) { dp[i-j][i+j] = 1; j++; } int x = i , y =i+1; while(x>=0 && y<len) { if(s[x]==s[y]) { dp[x][y]=1; x--; y++; } else break; } } int num = 0; if(dp[0][len-1]==1)return 0; vector<int> cut(len ,1); for(int i = 0 ; i < len ;i++) if(dp[0][i]==1)cut[i] = 1; else cut[i] = i+1; for(int i = 1;i<len;i++) { for(int j = 0 ;j <i ;j++) { if(j+1<len && dp[j+1][i]==1) { cut[i] = min(cut[j]+1,cut[i]); } } } return cut[len-1]-1; } };
posted on 2014-04-16 21:42 pengyu2003 阅读(106) 评论(0) 编辑 收藏 举报