Palindrome Partitioning

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.

思路:

  典型dfs+回溯

我的代码:

public class Solution {

    public List<List<String>> partition(String s) {

        if(s == null || s.length() == 0)    return rst;

        List<String> list = new ArrayList<String>();

        helper(s, list);

        return rst;

    }

    public void helper(String s, List<String> list)

    {

        if(s == null || s.length() == 0)

        {

            rst.add(new ArrayList(list));

            return;

        }

        for(int i = 1; i <= s.length(); i++)

        {

            String part = s.substring(0,i);

            if(isPalindrome(part))

            {

                list.add(part);

                helper(s.substring(i),list);

                list.remove(list.size() - 1);

            }

        }

    }

    private List<List<String>> rst = new ArrayList<List<String>>();

    public boolean isPalindrome(String part)

    {

        int len = part.length();

        for(int i = 0; i < len/2; i++)

        {

            char first = part.charAt(i);

            char last = part.charAt(len - 1 - i);

            if(first != last)   return false;

        }

        return true;

    }

}
View Code

 

你可能感兴趣的:(partition)