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"]
]
解题思路:
- 枚举的情况一般用递归来解决,本题也不例外
- 另外写一个递归函数,来求出所有可能的解
- 再写一个函数来判断字符串是否为回文串
代码如下:
public ArrayList<ArrayList<String>> partition(String s) {
// res 来存放所有的结果
ArrayList<ArrayList<String>> res = new ArrayList<>();
// 存放当前符合条件的字符串
ArrayList<String> list = new ArrayList<>();
partion(res,list,s);
return res;
}
// 递归函数
private void partion(ArrayList<ArrayList<String>> res, ArrayList<String> list, String s){
if(s == null || s.length() == 0){
res.add(new ArrayList<>(list));
return;
}
for(int i = 0; i <= s.length(); i++){
String tempS = s.substring(0,i);
if(isHuiwen(tempS)){
list.add(tempS);
partion(res, list, s.substring(i,s.length()));
list.remove(list.size() - 1);
}
}
}
// 判断当前字符串是否为回文串
private boolean isHuiwen(String s){
if(s == null || s.length() == 0) return false;
int i = 0;
int mid = s.length() / 2;
while(i < mid){
if(s.charAt(i) != s.charAt(s.length() - i - 1))
return false;
i++;
}
return true;
}