2020-05-03 131. Palindrome Partitioning Medium

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"]]


这题一开始想法是每个字符有两种情况:加到当前字符串,或加到下一个字符串。后来看了下别人的答案,其实直接先判断是否回文,再进行list的add操作,更省时间。


class Solution {

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

        // System.out.println("input: " + s);

        List<List<String>> res = new LinkedList<>();

        LinkedList<String> cur = new LinkedList<String>();

        backtrace(cur, res, s, 0);

        return res;

    }


    private void backtrace(LinkedList<String> cur, List<List<String>> res, String s, int index) {

        // System.out.println(String.format("cur: %s, index: %d, s: %s", Arrays.deepToString(cur.toArray()), index, s));

        if (index == s.length()) {

            res.add(new ArrayList<>(cur));

            return;

        }


        for (int r = index; r < s.length(); r++) {

            if (isPalindrome(s, index, r)) {

                cur.add(s.substring(index, r + 1));

                backtrace(cur, res, s, r + 1);

                cur.removeLast();

            }

        }

    }


    private boolean isPalindrome(String s, int l, int r) {

        while (l < r) {

            if (s.charAt(l) != s.charAt(r)) return false;

            l++; r--;

        }

        return true;

    }

}



还要吐槽leetcode,这题我完全一样的答案,提交上去有时候4ms,有时候2ms,弄得百分比也不一样,还以为代码还有哪里有问题,结果拷贝了2ms的答案跑出来也要5ms左右

©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

友情链接更多精彩内容