[Leetcode]Palindrome Partitioning

时间:2014-11-05 17:11:03   收藏:0   阅读:180

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"]
  ]


[解题思路]

由于要求列出所有的可能,直接上dfs


[代码]

class Solution {
public:
    vector<vector<string> > res;
    
    vector<vector<string>> partition(string s) {
        vector<string> partitions;
        dfs(partitions, s, 0);
        
        return res;
    }
    
    void dfs(vector<string> partitions, string &s, int idx) {
        if (idx >= s.size()) {
            if (partitions.size() > 0) {
                res.push_back(partitions);
            }
            return;
        }
        
        for (int i = idx; i < s.size(); ++i) {
            string cur = s.substr(idx, i - idx + 1);
            if (isPalindrome(cur)) {
                partitions.push_back(cur);
                dfs(partitions, s, i + 1);
                partitions.pop_back();
            }
        }
        
        return;
    }
    
    bool isPalindrome(string s) {
        int len = s.size();
        if (len <= 1) return true;
        
        int left = 0;
        int right = len - 1;
        while (left < right) {
            if (s[left] != s[right]) return false;
            ++left;
            --right;
        }
        return true;
    }
};


原文:http://blog.csdn.net/algorithmengine/article/details/40826161

评论(0
© 2014 bubuko.com 版权所有 - 联系我们:wmxa8@hotmail.com
打开技术之扣,分享程序人生!