131-Palindrome Partitioning

来源:互联网 发布:java axis2 调用wsdl 编辑:程序博客网 时间:2024/06/05 17:11
题目

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

分析
实现
/*Author: FancyDate:2017-03-21Algorithm:131-Palindrome PartitioningTime Compeliexity:*/class Solution {public:    vector<vector<string>> partition(string s) {        vector<vector<string>> res;        vector<string> curr;        if (s.empty())            return res;        dfs(res, curr, s, 0);        return res;    }    //深度遍历    void dfs(vector<vector<string>> &res, vector<string>& curr, string& s, int index)    {        //index == s.size时代表已经处理完该字符串        if (index == s.size())        {            res.push_back(curr);            return;        }        for (int i = index; i < s.size();i++)        //判断是否回文,如果是,则push,并递归处理剩余的字串            if (isPalindrome(s, index, i))            {                curr.push_back(s.substr(index, i - index + 1));                dfs(res, curr, s, i + 1);                //BackTracking                curr.pop_back();            }    }    //判断字符串是否回文    bool isPalindrome(string s, int start, int end)    {        if (start == end)            return true;        while (start < end )        {            if (s[start] != s[end])                return false;            start++;            end--;        }        return true;    }};
原创粉丝点击