[leetcode]Palindrome Partitioning

来源:互联网 发布:官方同花顺炒股软件 编辑:程序博客网 时间:2024/06/05 05:15


Palindrome Partitioning

 

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"]  ]
解题思路:用数组vvi[i][j]表示从第i个元素到第j个元素是回文串,然后再根据vvi[i][j]进行深度递归遍历收集合格的回文。
class Solution {public:    //判断字符串s [b,e]是不是回文    bool isPalindrome(string &s, int b, int e){        while(b < e){            if(s[b] != s[e]) return false;            b++; e--;        }        return true;    }    //s源串, 二维数组表示vvi[i, j]i到j是回文, b开始的行也可以指列,vs临时收集串,vvs最终输出的地方    void collectAll(string &s, vector<vector<bool> > &vvi, int b, vector<string> &vs, vector<vector<string> > &vvs){        int n = s.size();        if(b == n){             vvs.push_back(vs);            return;        }        for(int i = b; i < n; i++){            if(vvi[b][i]){ //如果vvi[b][i]为真表示b-i为回文串,否则一直查找到一个回文串为止                string str(s, b, i - b + 1);                vs.push_back(str);                collectAll(s, vvi, i + 1, vs, vvs); //递归是第i+1行的第i+1列                vs.pop_back();            }        }    }    vector<vector<string>> partition(string s) {        size_t n = s.size();        vector<vector<string> >vvs;        if(n == 0) return vvs;                vector<vector<bool> > vvi(n, vector<bool>(n, false));        //动态规划 vvi[i, j]表示从i到j是回文串        for(int i = 0; i < n; i++){            for(int j = i; j < n; j++){                vvi[i][j] = isPalindrome(s, i, j);            }        }        vector<string> vs;        collectAll(s, vvi, 0, vs, vvs);          return vvs;    }};

0 0