Palindrome Partitioning
Given s = "aab", return:
[
["aa","b"],
["a","a","b"]
]Basic Idea:
Java Code:
public class Solution {
/**
* @param s: A string
* @return: A list of lists of string
*/
// 把问题当做一个subset的问题,考虑所有的分割点位置
public List<List<String>> partition(String s) {
List<List<String>> res = new ArrayList<>();
if (s.length() == 0) {
res.add(new ArrayList<String>());
return res;
}
helper(s, new ArrayList<String>(), 0, res);
return res;
}
// 考虑从以pos字母开始的substring所有的分割位置,把符合要求的加入path,如果
// 全部符合要求,就把path加入res,return
private void helper(String str,
List<String> path,
int pos,
List<List<String>> res) {
if (pos == str.length()) {
res.add(new ArrayList<String>(path));
return;
}
for (int i = pos; i < str.length(); ++i) {
String substring = str.substring(pos, i + 1);
if (! isPalindrome(substring)) continue;
path.add(substring);
helper(str, path, i + 1, res);
path.remove(path.size() - 1);
}
}
private boolean isPalindrome(String str) {
for (int i = 0; i < str.length() / 2; ++i) {
if (str.charAt(i) != str.charAt(str.length() - 1 - i)) {
return false;
}
}
return true;
}
}