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"]
]

使用回溯法
class Solution {
List<List<String>>res;
public List<List<String>> partition(String s) {
res=new ArrayList();
if(s.length()==0)
return res;
if(s.length()==1){
ArrayList<String> temp=new ArrayList();
temp.add(s);
res.add(temp);
return res;
}
tryPartition(s,new ArrayList<String>());
return res;
}
//查找s中所有的回文字符串,temp保存的是之前所查找到的所有的回文字符串
private void tryPartition(String s,ArrayList<String> list){
if(s.length()==1){
list.add(s);
res.add(list);
return;
}
//0表示一位也不取,1表示从s中取出1个字符,2表示从s中取出2个字母
for(int i=1;i<=s.length();i++){
ArrayList<String>temp=new ArrayList();
if(i==s.length()&&isPalindrome(s)){
temp.addAll(list);
temp.add(s);
res.add(temp);
return;
}
String tempStr=s.substring(0,i);
if(!isPalindrome(tempStr))
continue;
temp.addAll(list);
temp.add(tempStr);
tryPartition(s.substring(i),temp);
}
}
private boolean isPalindrome(String s){
if(s.length()==1)
return true;
int l=0;
int r=s.length()-1;
while(l<r){
if(s.charAt(l++)!=s.charAt(r--))
return false;
}
return true;
}
}

本文介绍了一种利用回溯法解决回文字符串分割问题的方法,通过递归地尝试所有可能的分割方式,找出所有能将输入字符串分割成回文子串的方案。示例代码展示了如何实现这一算法,包括判断字符串是否为回文的辅助函数。
1831

被折叠的 条评论
为什么被折叠?



