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:
    vector<vector<string> > ans;
    //判断是不是回文
    bool IsPalindrome(const string& str, int start, int end)
    {
        if (start == end) {
            return true;
        }
        while (start < end) {
            if(str[start] != str[end])
                return false;
            ++start;
            --end;
        }
        return true;
    }
    
    void RecursivePartiton(string& s, int start, vector<string>& par)
    {
        if(start == s.size())
        {
            ans.push_back(par);
            return;
        }
        for(size_t i = start; i < s.size(); ++i)
        {
            //如果start 到 i是回文,则将其分割,从下个位置i+1起继续递归分割
            if (IsPalindrome(s, start, i)) {
                par.push_back(s.substr(start, i - start + 1));
                RecursivePartiton(s, i + 1, par);
                par.pop_back();//递归回溯
            }
        }
        
    }
    
    vector<vector<string> > partition(string s) {
        vector<string> par;
        par.clear();
        ans.clear();
        RecursivePartiton(s, 0, par);
        return ans;
    }
};


你可能感兴趣的:(LeetCode,面试,String,递归)