leetcode-Palindrome Partitioning

来源:互联网 发布:社交行为数据挖掘 编辑:程序博客网 时间:2024/06/09 20:25

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

Return all possible palindrome partitioning of s.

For example, given s = "aab",
Return

  [    ["aa","b"],    ["a","a","b"]  ]
class Solution {public:    bool IsPal(string s)    {        int n = s.length();        int i = 0;        int j = n-1;        while(i < j)        {            if(s[i++] != s[j--])return false;        }        return true;    }        void findPal(vector<vector<string>> &ret, vector<vector<string>> &v, vector<vector<bool>> &b, int l, int n, vector<string> ss)    {        if(l == n)        {            ret.push_back(ss);            return;        }                string s;        ss.push_back(s);        int m = ss.size();        for(int i = 0; i < n-l; i++)        {            if(b[i][l])            {                ss[m-1] = v[i][l];                findPal(ret,v,b,l+i+1,n,ss);            }        }    }    vector<vector<string>> partition(string s) {        vector<vector<string>>v;        vector<vector<bool>>pal;                vector<vector<string>>ret;        int n = s.length();        if(n==0)return ret;        for(int i = 1; i <= n; i++)        {            vector<string> a;            vector<bool>b;            for(int j = 0; j <= n-i; j++)            {                string s1;                s1.assign(s,j,i);                a.push_back(s1);                bool t = IsPal(s1);                b.push_back(t);                            }            v.push_back(a);            pal.push_back(b);        }        vector<string> ss;        findPal(ret,v,pal,0,n,ss);                return ret;    }};


0 0