Leetcode -- Palindrome Partitioning II

来源:互联网 发布:php文件管理系统代码 编辑:程序博客网 时间:2024/06/05 15:31

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 n=s.size();        vector<vector<bool>> f(n,vector<bool>(n,0));        for(int i=n-1;i>=0;--i)            for(int j=i;j<n;++j)                if(s[i]==s[j]&&(j-i<2||f[i+1][j-1]))                     f[i][j]=1;        vector<int> dp(n,0);        for(int i=n-2;i>=0;--i)        {            if(f[i][n-1]) continue;            int val=INT_MAX;            for(int j=i+1;j<n;++j)                if(f[i][j-1])                     val=min(val,dp[j]+1);            dp[i]=val;        }        return dp[0];    }};


0 0
原创粉丝点击