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
?
isPalindrome
:
backtrack
:
import java.util.ArrayList;
import java.util.List;
public class Solution {
public List<List<String>> partition(String s) {
List<List<String>> result = new ArrayList<>();
backtrack(s, 0, new ArrayList<>(), result);
return result;
}
private void backtrack(String s, int start, List<String> currentList, List<List<String>> result) {
if (start == s.length()) {
result.add(new ArrayList<>(currentList));
return;
}
for (int end = start + 1; end <= s.length(); end++) {
if (isPalindrome(s, start, end - 1)) {
currentList.add(s.substring(start, end));
backtrack(s, end, currentList, result);
currentList.remove(currentList.size() - 1);
}
}
}
private boolean isPalindrome(String s, int low, int high) {
while (low < high) {
if (s.charAt(low++) != s.charAt(high--)) {
return false;
}
}
return true;
}
public static void main(String[] args) {
Solution sol = new Solution();
String s = "aab";
List<List<String>> result = sol.partition(s);
System.out.println(result);
}
}
n
characters, there are 2^(n-1)
ways to partition n
characters.Palindrome Check Complexity: Checking each substring if it’s a palindrome takes O(n)
time.
n
is the length of the string:
O(n * 2^n)
.While this approach can handle small strings effectively, it might not scale well for very large strings due to the exponential nature of the problem.
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?