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

131. Palindrome Partitioning

时间:2017-10-03 00:52:13      阅读:157      评论:0      收藏:0      [点我收藏+]

标签:style   oid   ret   sub   art   color   tor   字符   ++   

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"]
]
解题思路:递归回溯,AC之后发现效率比别人的差了点,总结原因是每次判断子字符是否是回文的时候我都先求了字串,其实可以直接用位置来判断,然后在temp的push操作时再求substr
class Solution {
public:
    bool isPalindrome(string &s){
        for(int i=0,j=s.length()-1;i<j;i++,j--){
            if(s[i]!=s[j])return false;
        }
        return true;
    }
    void dfs(vector<vector<string>> &res, int begin, vector<string>&temp, string& s){
        if(begin==s.length()){
            res.push_back(temp);
            return;
        }
        for(int i=1;i+begin<=s.length();i++){
            string str=s.substr(begin,i);
            if(isPalindrome(str)){
                temp.push_back(str);
                dfs(res,begin+i,temp,s);
                temp.pop_back();
            }
        }
    }
    vector<vector<string>> partition(string s) {
        vector<vector<string>>res;
        vector<string>temp;
        dfs(res,0,temp,s);
        return res;
    }
};

 

131. Palindrome Partitioning

标签:style   oid   ret   sub   art   color   tor   字符   ++   

原文地址:http://www.cnblogs.com/tsunami-lj/p/7623034.html

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