131. Palindrome Partitioning
- Total Accepted: 84076
- Total Submissions: 272482
- Difficulty: Medium
- Contributors: Admin
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"] ]
Subscribe to see which companies asked this question
分析
在每一步都可以判断中间结果是否为合法结果,用回溯法
一个长度为n的字符串,有n-1个地方可以砍断,每个地方可断可不断,因此时间复杂度为O(2^n)
class Solution {
public:
vector<vector<string>> partition(string s) {
vector<vector<string>> result;
vector<string> path; // ???? partition ????
dfs(s, path, result, 0, 1);
return result;
}
void dfs(string &s, vector<string>& path,
vector<vector<string>> &result, size_t prev, size_t start) {
if (start == s.size()) {
if (isPalindrome(s, prev, start - 1)) {
path.push_back(s.substr(prev, start - prev));
result.push_back(path);
path.pop_back();
}
return;
}
dfs(s, path, result, prev, start + 1);
if (isPalindrome(s, prev, start - 1)) {
path.push_back(s.substr(prev, start - prev));
dfs(s, path, result, start, start + 1);
path.pop_back();
}
}
bool isPalindrome(const string &s, int start, int end) {
while (start < end && s[start] == s[end]) {
++start;
--end;
}
return start >= end;
}
};