LeetCode-----迴文串分割
阿新 • • 發佈:2019-01-26
迴文串分割
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”]
]
import java.util.*;
public class main {
public static void main (String[] args) {
Scanner sc=new Scanner(System.in);
String s="bb";
ArrayList<ArrayList<String>> list=partition(s);
for (ArrayList<String> l:list){
System.out.print(l);
}
}
public static ArrayList<ArrayList<String>> partition (String s) {
ArrayList<ArrayList<String>> list=new ArrayList<ArrayList<String>>();
list=partitionDi(s);
return list;
}
public static ArrayList<ArrayList<String>> partitionDi(String s) {
ArrayList<ArrayList<String>> res=new ArrayList<ArrayList<String>>();
if (s.length()==0){
return res;
}
if (s.length()==1){
ArrayList<String> inList=new ArrayList<String>();
inList.add(s);
res.add(inList);
return res;
}
for (int i=0;i<s.length();i++){
if (isPalindrome(s.substring(0,i+1))){
if (i==s.length()-1){
ArrayList<String> inList=new ArrayList<String>();
inList.add(s.substring(0,i+1));
res.add(inList);
}
ArrayList<ArrayList<String>> list=partitionDi(s.substring(i+1));
for (int j=0;j<list.size();j++){
ArrayList<String> inList=new ArrayList<String>();
inList.add(s.substring(0,i+1));
inList.addAll(list.get(j));
res.add(inList);
}
}
}
return res;
}
public static boolean isPalindrome(String s){
int i=0;
int j=s.length()-1;
while (i<j){
if (s.charAt(i)!=s.charAt(j)){
return false;
}
i++;
j--;
}
return true;
}
}