给定一个字符串 s,将 s 分割成一些子串,使每个子串都是回文串。
返回 s 所有可能的分割方案。
例如,给出 s = "aab",
返回
[
["aa","b"],
["a","a","b"]
]
详见:https://leetcode.com/problems/palindrome-partitioning/description/
Java实现:
class Solution {
public List<List<String>> partition(String s) {
List<List<String>> res=new ArrayList<List<String>>();
if(s.isEmpty()){
return res;
}
helper(s,0,new ArrayList<String>(),res);
return res;
}
private void helper(String s,int start,List<String> out,List<List<String>> res){
if(start==s.length()){
res.add(new ArrayList<String>(out));
return;
}
for(int i=start;i<s.length();++i){
if(isPalindrome(s,start,i)){
out.add(s.substring(start,i+1));
helper(s,i+1,out,res);
out.remove(out.size()-1);
}
}
}
private boolean isPalindrome(String s,int start,int end){
while(start<end){
if(s.charAt(start)!=s.charAt(end)){
return false;
}
++start;
--end;
}
return true;
}
}