leetcode: Palindrome Partitioning II解法

来源:互联网 发布:淘宝热销商品 编辑:程序博客网 时间:2024/06/05 08:04

题目如下:

Given a string s, partition s such thatevery substring of the partition is a palindrome.

Return the minimum cuts needed for apalindrome partitioning of s.

For example, given s = "aab",
Return 
1 since thepalindrome partitioning ["aa","b"] could be produced using 1 cut.

这个题目的解法是动态规划。首先用b这个矩阵来代表s[i]-s[j]是否是palindrome。b[i][j]==true 意思是s[i]到s[j]事palindrome。 

之后用result来动态计算s[0]-s[j]的最小cut,每一次看判断最小值。

class Solution {public:    int minCut(string s) {        // Start typing your C/C++ solution below        // DO NOT write int main() function         int len=s.length();        if(len<1) return 0;                vector<bool> temp(len,false);        vector<vector<bool>> b(len,temp);                int i;                for(i=0;i<len;i++)        {            b[i][i]=true;        }                for(i=0;i<len-1;i++)        {            if(s[i]==s[i+1])            b[i][i+1]=true;        }                int l;        for(l=3;l<=len;l++)        {            for(i=0;i<=len-l;i++)            {                int j=i+l-1;                if(s[i]==s[j] && b[i+1][j-1])                b[i][j]=true;                            }        }                int min=helper(b,s);        return min;    }        int helper(vector<vector<bool>>& b, string s)    {        vector<int> result(s.length(),0);        result[0]=0;                for(int j=0; j<s.length(); j++)        {            int min=j;            if(b[0][j]) result[j]=0;            else            {                for(int i=1;i<=j;i++)                {                    if(b[i][j] && result[i-1]+1<=min)                    min=result[i-1]+1;                }                result[j]=min;               }        }        return result[s.length()-1];    }};


原创粉丝点击