DP动态规划专题四 :LeetCode 132. Palindrome Partitioning

LeetCode 132. 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.

Example:

Input: "aab"
Output:
[
  ["aa","b"],
  ["a","a","b"]
]

思路还是一样,n的答案依赖于0~n-1的答案

    public List<List<String>> partition(String s) {
        List<List<List<String>>> allResult = new ArrayList<>();
        List<List<String>> res = new ArrayList<>();
        if (s.length() == 0) return res;
        List<String> l = new ArrayList<>();
        l.add(s.substring(0,1));
        res.add(l);
        allResult.add(res);
        for (int i = 1; i < s.length(); i++) {
            List<List<String>> curRes = new ArrayList<>();
            for (int p = 0; p <= i; p++) {
                String curs = s.substring(p,i+1);
                if (isPalindrome(curs)) {
                    List<List<String>> pre = new ArrayList<>();
                    List<String> a = new ArrayList<>();
                    pre.add(a);
                    if (p != 0) pre = allResult.get(p-1);
                    for (List<String> ll : pre) {
                        List<String> lll = new ArrayList<>(ll);
                        lll.add(curs);
                        curRes.add(lll);
                    }
                }
            }
            allResult.add(curRes);
        }
        List<List<String>> result = allResult.get(allResult.size() - 1);
        return result;
    }
    private boolean isPalindrome(String s) {
        if (s.length() <= 1) return true;
        int l = 0;
        int r = s.length() - 1;
        while (l < r) {
            if (s.charAt(l++) != s.charAt(r--)) {
                return false;
            }
        }
        return true;
    }

猜你喜欢

转载自blog.csdn.net/katrina95/article/details/85381738