Simple java solution


  • 2
    H
    public List<List<String>> partition(String s) {
        // in thie problem, ArrayList runs faster than LinkedList
        List<List<String>> res = new ArrayList<>();
        List<String> pre = new ArrayList<>();
        part(s, res, pre);
        return res;
    }
    private void part(String s, List<List<String>> res, List<String> pre) {
        if (s.equals("")) {
            res.add(pre);
            return;
        }
        for (int i = 1; i <= s.length(); i++) {
            if (isPal(s.substring(0, i))) {
                pre.add(s.substring(0, i));
                part(s.substring(i), res, new ArrayList(pre));
                pre.remove(pre.size() - 1);
            }
        }
        return;
    }
    private boolean isPal(String s) {
        if (s.equals("")) {return true;}
        int p1 = 0, p2 = s.length() - 1;
        while (p1 < p2) {
            if (s.charAt(p1) == s.charAt(p2)) {
                p1++;
                p2--;
            } else {return false;}
        }
        return true;
    }

Log in to reply
 

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