Leetcode 131. 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
.
Example:
Input: s = "aab"
Output: [["a","a","b"],["aa","b"]]
s
always non-empty?
s
is always non-empty.s
consist of any characters other than lowercase or uppercase alphabets?
The problem can be approached using a backtracking algorithm. Here’s the step-by-step strategy:
s
.isPalindrome
will be used to check whether a given substring is a palindrome.#include <vector>
#include <string>
#include <iostream>
using namespace std;
class Solution {
public:
vector<vector<string>> partition(string s) {
vector<vector<string>> result;
vector<string> current;
backtrack(result, current, s, 0);
return result;
}
private:
void backtrack(vector<vector<string>>& result, vector<string>& current, const string& s, int start) {
if (start == s.size()) {
result.push_back(current);
return;
}
for (int end = start; end < s.size(); ++end) {
if (isPalindrome(s, start, end)) {
current.push_back(s.substr(start, end - start + 1));
backtrack(result, current, s, end + 1);
current.pop_back();
}
}
}
bool isPalindrome(const string& s, int left, int right) {
while (left < right) {
if (s[left] != s[right]) return false;
++left;
--right;
}
return true;
}
};
int main() {
Solution sol;
string input = "aab";
vector<vector<string>> result = sol.partition(input);
for (const auto& partition : result) {
for (const auto& str : partition) {
cout << str << " ";
}
cout << endl;
}
return 0;
}
Thus, the time complexity can be approximated to (O(n \cdot 2^n)) due to the nested nature of the backtracking and palindrome check operations.
current
.This solution effectively balances both clarity and efficiency for the given problem constraints.
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?