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);
    }
}

 

 

 

相关文章:

  • 2021-12-19
  • 2021-07-04
  • 2021-09-09
  • 2022-01-01
  • 2021-06-07
  • 2021-11-09
  • 2021-10-23
猜你喜欢
  • 2021-08-04
  • 2021-08-01
  • 2021-12-14
  • 2021-10-31
相关资源
相似解决方案