leetcode [131]Palindrome Partitioning

Given a string s, partition s such that every substring of the partition is a palindrome.

Return all possible palindrome partitioning of s.

Example:

Input: "aab"
Output:
[
  ["aa","b"],
  ["a","a","b"]
]

题目大意:

找出字符串s所有子串划分,子串划分满足每个子串都是回文串。

解法:

采用深度优先遍历。

java:

class Solution {
    void helper(String s,int index,List<List<String>>res,List<String>tmp){
        if(index==s.length()){
            res.add(new ArrayList<>(tmp));
            return;
        }
        for(int i=index+1;i<=s.length();i++){
            if(isRight(s,index,i)){
                tmp.add(s.substring(index,i));
                helper(s,i,res,tmp);
                tmp.remove(tmp.size()-1);
            }
        }
    }

    boolean isRight(String s,int start,int end){
        if(start>=end) return false;
        end--;
        while(start<end){
            if(s.charAt(start)!=s.charAt(end)) return false;
            start++;
            end--;
        }
        return true;
    }

    public List<List<String>> partition(String s) {
        List<List<String>>res=new ArrayList<>();
        List<String>tmp=new ArrayList<>();
        helper(s,0,res,tmp);
        return res;
    }
}

  

posted @ 2019-04-16 11:42  小白兔云  阅读(85)  评论(0)    收藏  举报