标签:leetcode palindrome partition
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 class Solution {
public List<List<String>> partition(String s) {
List<List<String>> res = new ArrayList<>();
List<String> list = new ArrayList<String>();
dfs(s, list, res);
return res;
}
public void dfs(String s,List<String> list,List<List<String>> res){
if(s.length()<1){
//巨大错误:!!! 这里必须注意不能写成res.add(list); 因为后面list会改变,导致最终res里面为空
res.add(new ArrayList<String>(list));
return;
}
for(int i=0;i<s.length();i++){
if(IsPalindrome(0, i, s)){
list.add(s.substring(0,i+1));
dfs(s.substring(i+1), list, res);
list.remove(list.size()-1);
}
}
}
boolean IsPalindrome(int start ,int end,String s){
while(start<end){
if(s.charAt(start)==s.charAt(end)){
start++;
end--;
}else {
return false;
}
}
return true;
}
}public List<List<String>> partition(String s) {
List<String> item = new ArrayList<String>();
List<List<String>> res = new ArrayList<>();
if(s==null||s.length()==0)
return res;
dfs(s,0,item,res);
return res;
}
public void dfs(String s, int start, List<String> item, List<List<String>> res){
if (start == s.length()){
res.add(new ArrayList<String>(item));
return;
}
for (int i = start; i < s.length(); i++) {
String str = s.substring(start, i+1);
if (isPalindrome(str)) {
item.add(str);
dfs(s, i+1, item, res);
item.remove(item.size() - 1);
}
}
}
public boolean isPalindrome(String s){
int low = 0;
int high = s.length()-1;
while(low < high){
if(s.charAt(low) != s.charAt(high))
return false;
low++;
high--;
}
return true;
}
}标签:leetcode palindrome partition
原文地址:http://blog.csdn.net/huruzun/article/details/39209319