My concise java solution, 20 lines


  • 0
    H
    public List<List<String>> partition(String s) {
        List<List<String>> output = new ArrayList<List<String>>();
        helper(output, new ArrayList<String>(), s);
        return output;
    }    
    private void helper(List<List<String>> output, List<String> list, String s) {
        if (s.length() == 0) {output.add(list); return;}
        for (int i = 1; i <= s.length(); i++) {
            List<String> tmp = new ArrayList<String>(list);
            if (isPalindrome(s.substring(0, i))) {
                tmp.add(s.substring(0, i));
                helper(output, tmp, s.substring(i));
            }
        }
    } 
    private boolean isPalindrome(String s) {
        for (int i = 0, j = s.length() - 1; i < j; i++, j--)
            if (s.charAt(i) != s.charAt(j)) return false;
        return true;
    }

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.