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"] ]
给定一个指针从字符串从前往后移动,从开头到该指针的字符串是回文,则递归剩下后面部分字符串。
代码如下:
class Solution { public List<List<String>> partition(String s) { List<List<String>> res=new ArrayList<List<String>>(); if(s==null||s.length()==0) return res; helper(res,new ArrayList<String>(),s,0); return res; } public void helper(List<List<String>> res,List<String> list,String s,int index){ if(index==s.length()){ res.add(new ArrayList<String>(list)); return ; } for(int i=index;i<s.length();i++){ String sub=s.substring(index,i+1); if(isP(sub)){ list.add(sub); helper(res,list,s,i+1); list.remove(list.size()-1); } } } public boolean isP(String s){ StringBuilder sb=new StringBuilder(s); return sb.reverse().toString().equals(s); } }