zoukankan      html  css  js  c++  java
  • 【Lintcode】136.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.

    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;
        }
    };
  • 相关阅读:
    Java学习:Scanner类
    Java学习:Object类
    js 方法
    ToDictionary
    goto
    删除多列同时重复数据
    linq中使用case when
    sql 学习笔记
    VS2012发布网站详细步骤
    由于权限不足而无法读取配置文件出现的HTTP 500.19解决办法
  • 原文地址:https://www.cnblogs.com/Atanisi/p/6869609.html
Copyright © 2011-2022 走看看