Wednesday, September 24, 2014

Palindrome Partitioning

//dfs, backtraking

    vector<vector<string>> partition(string s) {
        vector<vector<string>> res;
        vector<string> part;
        partitionRe(s, 0, part,res);
        return res;
    }
    void partitionRe(const string &s, int start, vector<string> &part,vector<vector<string>> &res) {
        if (start == s.size())
        {
            res.push_back(part);
            return;
        }
        string palindrom;
        for (int i = start; i < s.size(); ++i) {
            palindrom.push_back(s[i]);
            if (!isPalindrome(palindrom)) continue;
            part.push_back(palindrom);
            partitionRe(s, i + 1, part,res);
            part.pop_back();
        }
    }
    bool isPalindrome(const string &s) {
        int i = 0, j = s.size()-1;
        while (i < j) {
        if (s[i] != s[j]) return false;
        i++; j--;
        }
        return true;
    }

No comments:

Post a Comment