- Palindrome Partitioning
Given a string s. Partition s such that every substring in the partition is a palindrome.
Return all possible palindrome partitioning of s.
Example
Example 1:
Input: “a”
Output: [[“a”]]
Explanation: Only 1 char in the string, only 1 way to split it (itself).
Example 2:
Input: “aab”
Output: [[“aa”, “b”], [“a”, “a”, “b”]]
Explanation: There are 2 ways to split “aab”.
1. Split “aab” into “aa” and “b”, both palindrome.
2. Split “aab” into “a”, “a”, and “b”, all palindrome.
Notice
Different partitionings can be in any order.
Each substring must be a continuous segment of s.
解法1:DFS。
代码如下:
class Solution {
public:
/*
* @param s: A string
* @return: A list of lists of string
*/
vector<vector<string>> partition(string &s) {
vector<vector<string> > results;
if (s.empty()) {
results.push_back(vector<string>());
return results;
}
vector<string> sol;
helper(s, 0, sol, results);
return results;
}
bool isPalidrome(string &s) {
int len = s.size();
if (len < 2) return true;
int i = 0, j = len - 1;
while (i < j) {
if (s[i] != s[j])
return false;
i++; j--;
}
return true;
}
void helper(string &s, int index, vector<string> &sol, vector<vector<string>> & results) {
int len = s.size();
if (index >= len) {
results.push_back(sol);
return;
}
for (int i = index; i < len; ++i) {
string str = s.substr(index, i - index + 1);
if (isPalidrome(str)) {
sol.push_back(str);
helper(s, i + 1, sol, results);
sol.pop_back();
}
}
}
};
这个DFS就是用挡板法,从n-1个空隙中挑位置。
如何优化?可以先做预处理,这里判断是不是Palidrome直接用数组返回结果即可,不用再调用IsPalidrome()了。
本文介绍了一种使用深度优先搜索(DFS)解决回文字符串分割问题的方法,通过递归地检查字符串子集是否为回文,并记录所有可能的分割方式。
271

被折叠的 条评论
为什么被折叠?



