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"] ]
这道题让我们找出所有合法的回文子字符串分割。可以基于回溯的思想来实现。
对于当前的index, 我们找出以当前index开始的可能的回文字符,并把他们加到列表里面,然后对后面剩下的字符串再进行递归判断。
比如当index = 0的时候,第一个回文字符串我们可以选择 "a"切割,也可以选择"aa"切割。
为了更加高效,基于动态规划的思想判断是否为回文,创建isPal的二维数组, isPal[ i ] [ j ] 存储 index从 i 到 j 的子字符串是否回文。
未优化前的运行时间:
未优化的代码:
public class PalindromePartitioning {
public List<List<String>> partition(String s) {
List<List<String>> result = new ArrayList<>();
doPartition(result, new ArrayList<>(), s, 0);
return result;
}
private void doPartition(List<List<String>> result, List<String> curList, String s, int begin) {
if (begin == s.length()) {
result.add(new ArrayList<>(curList));
}
for (int i = begin; i < s.length(); i++) {
if (i == begin) {
curList.add(s.charAt(i) + "");
doPartition(result, curList, s, begin + 1);
curList.remove(curList.size() - 1);
} else {
String temp = s.substring(begin, i + 1);
if (isPalidrome(temp)) {
curList.add(temp);
doPartition(result, curList, s, begin + temp.length());
curList.remove(curList.size() - 1);
}
}
}
}
private boolean isPalidrome(String s) {
int left = 0, right = s.length() - 1;
while (left < right) {
if (s.charAt(left) != s.charAt(right)) {
return false;
}
left++;
right--;
}
return true;
}
}
基于动态规划的优化后的运行时间:
代码:
public List<List<String>> partition(String s) {
List<List<String>> result = new ArrayList<>();
boolean[][] isPal = new boolean[s.length()][s.length()];
for (int i = s.length() - 1; i >= 0; i--) {
for (int j = i; j < s.length(); j++) {
if (( i + 1 > j - 1 || isPal[i + 1][j - 1]) && s.charAt(i)== s.charAt(j))
isPal[i][j] = true;
}
}
doPartition(result, new ArrayList<>(), isPal, s, 0);
return result;
}
private void doPartition(List<List<String>> result, List<String> curList, boolean[][] isPal, String s, int begin) {
if (begin == s.length()) {
result.add(new ArrayList<>(curList));
}
for (int i = begin; i < s.length(); i++) {
if (isPal[begin][i]) {
String temp = s.substring(begin, i + 1);
curList.add(temp);
doPartition(result, curList, isPal, s, i + 1);
curList.remove(curList.size() - 1);
}
}
}