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

class Solution {
public:
    bool isPalindrome(const string &s, int first, int last) {
        if (first == last)
            return true;
        while (first < last) {
            if (s[first]!=s[last])
                return false;
            first++;
            last--;
        }
        return true;
    }
    
    void _partition(const string &s, int first, vector<string> par) {
        if (first == s.length())    
            result.push_back(par);
        int i;
        for (i=first;i<s.length();i++) {
            if (isPalindrome(s, first, i)) {
                par.push_back(s.substr(first, i-first+1));
                _partition(s, i+1, par);
                par.pop_back();
            }
        }
    }
    
    vector<vector<string> > partition(string s) {
        result.clear();
        vector<string> par;
        _partition(s, 0, par);
        return result;
    }
    vector<vector<string> > result;
};


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章