描述
给定一个字符串s,将s分割成一些子串,使每个子串都是回文串。
返回s所有可能的回文串分割方案。
您在真实的面试中是否遇到过这个题?
是
样例
给出 s = "aab"
,返回
[
["aa", "b"],
["a", "a", "b"]
]
分析:因为这道题需要遍历所有的字符,所以可以用DFS求解,
既然题目要求找到所有可能拆分成回文数的情况,那么肯定是所有的情况都要遍历到,对于每一个子字符串都要分别判断一次是不是回文数,那么肯定有一个判断回文数的子函数,还需要一个DFS函数用来递归,再加上原本的这个函数,总共需要三个函数来求解。代码如下:
class Solution { public: vector<vector<string>> partition(string s) { vector<vector<string>> res; vector<string> out; partitionDFS(s, 0, out, res); return res; } void partitionDFS(string s, int start, vector<string> &out, vector<vector<string>> &res) { if (start == s.size()) { res.push_back(out); return; } for (int i = start; i < s.size(); ++i) { if (isPalindrome(s, start, i)) { out.push_back(s.substr(start, i - start + 1)); partitionDFS(s, i + 1, out, res); out.pop_back(); } } } bool isPalindrome(string s, int start, int end) { while (start < end) { if (s[start] != s[end]) return false; ++start; --end; } return true; } };
那么,对原字符串的所有子字符串的访问顺序是什么呢,如果原字符串是 abcd, 那么访问顺序为: a -> b -> c -> d -> cd -> bc -> bcd-> ab -> abc -> abcd, 这是对于没有两个或两个以上子回文串的情况。那么假如原字符串是 aabc,那么访问顺序为:a -> a -> b -> c -> bc -> ab -> abc -> aa -> b -> c -> bc -> aab -> aabc,中间当检测到aa时候,发现是回文串,那么对于剩下的bc当做一个新串来检测,于是有 b -> c -> bc,这样扫描了所有情况,即可得出最终答案。