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) { int len=s.length(); if(len==0||len==1)return 0; //构造回文判别矩阵 vector<vector<bool> > isPal(len, vector<bool>(len, false)); //初始化isPal[i][i] for(int i=0; i<len; i++) isPal[i][i]=true; //初始化isPal[i][i+1] for(int i=0; i<len-1; i++) if(s[i]==s[i+1])isPal[i][i+1]=true; //初始化其他i<j的子串 for(int i=len-3; i>=0; i--) for(int j=i+2; j<len; j++) isPal[i][j]=(s[i]==s[j])&&isPal[i+1][j-1]; //求最小切割 vector<int> minCuts(len, 0); //记录以i结尾的子串的最小切分数 for(int i=0; i<len; i++){ int mincut=INT_MAX; for(int j=-1; j<i; j++){ if(isPal[j+1][i]){ if(j==-1)mincut=0; else if(minCuts[j]+1<mincut)mincut=minCuts[j]+1; } } if(mincut!=INT_MAX)minCuts[i]=mincut; } return minCuts[len-1]; } };
LeetCode: Palindrome Partitioning II [132],布布扣,bubuko.com
LeetCode: Palindrome Partitioning II [132]
原文地址:http://blog.csdn.net/harryhuang1990/article/details/34530861