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: "aab"
Output:
[
["aa","b"],
["a","a","b"]
]
Solution
It reaches the ith charater when partitioning:
- Try every
j (j >= i)to check if the substring between theithandjthcharacter is palindrome - If it’s palindrome, partition the substring after the
jthcharacter
例如,Input: "aab"
- 首先访问第一个a,Try every
j (j >= i)to check if the substring between theithandjthcharacter is palindrome ==》 从index 0切开,首先判断,a是不是回文,如果是,则将其加入substringEntry,然后继续迭代处理index 0 以后substringab。 - 再try next j, 从
index 1切开,判断aa是不是回文,如果是,则将其加入substringEntry,然后继续迭代处理index以后substringb`. - Base case:
current index == str.length (), 表示整个String已经被访问了一遍,将substringsEntry加入结果并返回。
class Solution {
public List<List<String>> partition(String s) {
List<List<String>> result = new ArrayList<> ();
if (s.length () == 0 || s == null) {
return result;
}
List<String> subStringsEntry = new ArrayList<> ();
partitionHelper (s, result, subStringsEntry, 0);
return result;
}
private void partitionHelper (String str, List<List<String>> result, List<String> subStringsEntry, int start) {
if (start == str.length ()) {
result.add (new ArrayList<> (subStringsEntry));
return;
}
// solution:
// It reaches the ith charater when partitioning:
// Try every j (j >= i) to check if the substring between the ith and jth character is palindrome
// If it’s palindrome, partition the substring after the jth character
for (int i = start; i < str.length (); i ++) {
if (isPalindrome (str, start, i)) {
subStringsEntry.add (str.substring(start, i + 1));
partitionHelper (str, result, subStringsEntry, i + 1);
subStringsEntry.remove (subStringsEntry.size() - 1);
}
}
}
private boolean isPalindrome (String str, int start, int end) {
while (start < end) {
if (str.charAt (start) != str.charAt (end)) {
return false;
}
start ++;
end --;
}
return true;
}
}