[LeetCode] 131. Palindrome Partitioning

来源:互联网 发布:泰国人用淘宝吗 编辑:程序博客网 时间:2024/06/07 01:01

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:    vector<vector<string>> partition(string s) {        vector<vector<string>> res;        vector<string> comb;        partition(res, comb, s, 0);        return res;    }private:    void partition(vector<vector<string>>& res, vector<string>& comb, string& s, int base) {        if (base == s.length()) {            res.push_back(comb);            return;        }        for (int i = base; i < s.length(); i++) {            if (IsPalindrome(s, base, i)) {                comb.push_back(s.substr(base, i - base + 1));                partition(res, comb, s, i + 1);                comb.pop_back();            }        }    }    bool IsPalindrome(string& s, int i, int j) {        for (; i <= j && s[i] == s[j]; i++, j--)            ;        return i > j;    }};

这里写图片描述这里写图片描述

原创粉丝点击