LeetCode 131 Palindrome Partitioning

来源:互联网 发布:淘宝如何更换账户开店 编辑:程序博客网 时间:2024/05/16 10:04

题目描述

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

Return all possible palindrome partitioning of s.

For example, given s = “aab”,
Return

这里写图片描述

分析

这个问题,明显可以分解成子问题的解。

分别求s[0..i]作为第一个字符串,如果是palindrome,则解为s[0..i] + partition(s[i+1…end])

partition(s)=s[0..i]+partition(s[i+1...end])

代码

    public static List<List<String>> partition(String s) {        List<List<String>> rt = new ArrayList<List<String>>();        if ("".equals(s)) {            return rt;        }        if (s.length() == 1) {            rt.add(Arrays.asList(s));            return rt;        }        for (int i = 0; i < s.length(); i++) {            String x = s.substring(0, i + 1);            List<List<String>> sub = new ArrayList<List<String>>();            if (isPal(x)) {                sub = partition(s.substring(i + 1));                if (sub.isEmpty()) {                    rt.add(Arrays.asList(x));                } else {                    for (List<String> l : sub) {                        List<String> _l = new ArrayList<String>();                        _l.add(x);                        _l.addAll(l);                        rt.add(_l);                    }                }            }        }        return rt;    }    static boolean isPal(String s) {        int st = 0, ed = s.length() - 1;        while (st < ed) {            if (s.charAt(st++) != s.charAt(ed--)) {                return false;            }        }        return true;    }
0 0