题目:
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"] ]
题意:
给定一个字串,我们需要将字串拆解,每个字串必须是回文的(就是正着读倒着读一样),请将所有的拆解找到
解答:
这题我使用了递归,每次我们从字串的一个点出发,分别试探 1格 ,2格。。。n格是否为回文,如果是,将起点移到回文串之后继续寻找,直到找到头返回。
代码:
class Solution {
public List<List<String>> partition(String s) {
List<List<String>> res=new ArrayList<List<String>>();
recure(res,new ArrayList<String>(),s);
return res;
}
public void recure(List<List<String>> res,List<String> temp,String s){
if(s.length()==0) {
res.add(new ArrayList<String>(temp));
return ;
}
for(int i=0;i<s.length();i++){
if(isPalin(s.substring(0,i+1))){
temp.add(s.substring(0,i+1));
recure(res,temp,s.substring(i+1));
temp.remove(temp.size()-1);
}
}
}
public boolean isPalin(String s){
for(int i=0;i<s.length()/2;i++){
if(s.charAt(i)!=s.charAt(s.length()-1-i))
return false;
}
return true;
}
}
640

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



