LeetCode Palindrome Partitioning II(***)

来源:互联网 发布:富途证券 知乎 编辑:程序博客网 时间:2024/05/17 22:38

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 ofs.

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

       首先,遍历s,求出所有的回文,存放在二维数组中,对于flag[i][j],如果s[i..j]为回文,则flag[i][j]=1,否则flag[i][j]=0;

       然后,对于最小的剪切次数,可以通过DP思想,从s[0]开始往s[s.length()-1],求最小的剪切次数f[0]...f[s.length()-1]。

       时间复杂度为O(n^2)。

       备注:对于a+b=c?1:2,与a+(b=c?1:2)是不相同的!

class Solution {public:    vector<vector<int> > flag;    void buildFlag(string s){        vector<int> temp;        for(int i=0;i<s.length();i++)temp.push_back(0);        for(int i=0;i<s.length();i++)flag.push_back(temp);        for(int i=0;i<s.length();i++){            int tempi=i,tempj=i;            while(tempi>=0&&tempj<s.length()&&s[tempi]==s[tempj]){flag[tempi][tempj]=1;tempi--;tempj++;}            tempi=i;tempj=i+1;            while(tempi>=0&&tempj<s.length()&&s[tempi]==s[tempj]){flag[tempi][tempj]=1;tempi--;tempj++;}        }    }    int minCut(string s) {        if(s.length()<=1)return 0;        buildFlag(s);        int *f = new int[s.length()];        f[0]=0;        for(int i=1;i<s.length();i++){            f[i]=f[i-1]+1;            if(flag[0][i])f[i]=0;            else {                for(int j=0;j<i;j++)                f[i]=min(f[i],f[j]+(flag[j+1][i]==1?1:(i-j)));//如果用==?:,一定要注意运算符的优先级            }        }        return f[s.length()-1];    }};

0 0
原创粉丝点击