码迷,mamicode.com
首页 > 其他好文 > 详细

【Lintcode】136.Palindrome Partitioning

时间:2017-05-17 22:09:47      阅读:228      评论:0      收藏:0      [点我收藏+]

标签:else   lint   sub   ntc   ring   ssi   dfs   rom   back   

题目:

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

Return all possible palindrome partitioning of s.

Example

Given s = "aab", return:

[
  ["aa","b"],
  ["a","a","b"]
]

题解:

Solution 1 ()

class Solution {
public:
    vector<vector<string>> partition(string s) {
        if (s.empty()) {
            return {{}};
        }
        vector<vector<string> > res;
        vector<string> v;
        dfs(res, v, s, 0);
        
        return res;
    }
    void dfs(vector<vector<string> > &res, vector<string> &v, string s, int pos) {
        if (pos >= s.size()) {
            res.push_back(v);
            return;
        }
        string str;
        for (int i = pos; i < s.size(); ++i) {
            str += s[i];
            if (isValid(str)) {
                v.push_back(str);
                dfs(res, v, s, i + 1);
                v.pop_back();
            }
        }
    }
    bool isValid(string str) {
        if (str.empty()) {
            return true;
        }
        int begin = 0;
        int end = str.size() - 1;
        for (; begin <= end; ++begin, --end) {
            if (str[begin] != str[end]) {
                return false;
            }
        }
        return true;
    }
};

Solution 1.2 ()

class Solution {
public:
    bool isPalindrome(string &s, int i, int j){
        while(i < j && s[i] == s[j]){
            i++;
            j--;
        }
        if(i >= j) {
            return true;
        } else {
            return false;
        }
    }
    void helper(vector<vector<string>> & res, vector<string> &cur, string &s, int pos){
        if(pos == s.size()){
            res.push_back(cur);
            return;
        }
        for(int i = pos; i <= s.size() - 1; i++){
            if(isPalindrome(s, pos, i)){
                cur.push_back(s.substr(pos, i - pos + 1));
                helper(res, cur, s, i+1);
                cur.pop_back();
            }
        }
    }
    vector<vector<string>> partition(string s) {
        vector<vector<string>> res;
        vector<string> cur;
        helper(res, cur, s, 0);
        
        return res;
    }
};

 

【Lintcode】136.Palindrome Partitioning

标签:else   lint   sub   ntc   ring   ssi   dfs   rom   back   

原文地址:http://www.cnblogs.com/Atanisi/p/6869609.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!