*LeetCode-Palindrome Partitioning

和以前的backtracking一样 只是需要多了一个check是否是palindrome的函数

不要被吓倒 

public class Solution {
    public List<List<String>> partition(String s) {
        List<List<String>> res = new ArrayList<List<String>>();
        List<String> list = new ArrayList<String>();
        backtrack ( res, list, 0, s);
        return res;
    }
    public void backtrack ( List<List<String>> res, List<String> list, int start, String s){
        if ( start >= s.length() ){
            res.add(new ArrayList<String>(list));
            return;
        }
        for ( int i = start; i < s.length(); i++ ){
            if ( isPalin (s, start, i )) {
                list.add( s.substring ( start, i + 1 ));
                backtrack ( res, list, i + 1, s );
                list.remove( list.size() - 1 );
            }
        }
    }
    public boolean isPalin ( String s, int begin, int end ){
        if ( begin == end )
            return true;
        while ( begin < end ){
            if ( s.charAt( begin ) != s.charAt( end ) )
                return false;
            begin ++;
            end --;
        }
        return true;
    }
}


你可能感兴趣的:(*LeetCode-Palindrome Partitioning)