一、题目
二、代码
class Solution
{
List<List<String>> re_list = new LinkedList<>();
LinkedList<String> temp_list = new LinkedList<>();
// StringBuilder str = new StringBuilder();
public boolean whether(String str)
{
if(str.length()==0) return false;
int i;
int length ;
length = str.length();
for(i=0;i<length/2;i++)
{
if(str.charAt(i)!=str.charAt(length-1-i)) return false;
}
return true;
}
public void back(String s ,int start)
{
System.out.println("start " +start);
int i;
int length;
length = s.length();
if(start == length)
{
// System.out.println("长度符合要求");
int length_list = temp_list.size();
boolean temp_bool = true;
for(i=0;i<length_list;i++)
{
if(whether(temp_list.get(i))==false)
{
temp_bool=false;
break;
}
}
if(temp_bool==true) re_list.add(new LinkedList(temp_list));
}
if(start > length) return;
length = s.length();
for(i=start+1;i<=length;i++)
{
temp_list.add(s.substring(start,i));
// System.out.println("切割 " +s.substring(start,i));
back(s,i);
temp_list.removeLast();
}
}
public List<List<String>> partition(String s)
{
back(s,0);
// System.out.println(whether(str));
return re_list;
}
}
三、运行结果
四、附录
二刷
class Solution
{
List<List<String>> re = new LinkedList<>();
List<String> path = new LinkedList<>();
public boolean whether(String s)
{
int i;
int length = s.length();
for(i=0;i<length/2;i++)
{
if(s.charAt(i)!=s.charAt(length-1-i)) return false;
}
return true;
}
public void track(String s,int start)
{
int i;
int length = s.length();
//System.out.println(" start "+start);
if(start == length) re.add(new LinkedList<>(path));
if(start>length) return;
for(i=start+1;i<=length;i++)
{
String temp = s.substring(start,i);
if(whether(temp) == true)
{
//System.out.println(" 为真 "+" start "+start+" i "+i+" ");
path.add(s.substring(start,i));
track(s,i);
path.removeLast();
}
}
}
public List<List<String>> partition(String s)
{
//System.out.println(" "+whether("aab"));
track(s,0);
return re;
}
}