美文网首页
131. Palindrome Partitioning

131. Palindrome Partitioning

作者: 7ccc099f4608 | 来源:发表于2020-03-17 00:11 被阅读0次

https://leetcode-cn.com/problems/palindrome-partitioning/

image.png

(图片来源https://leetcode-cn.com/problems/palindrome-partitioning/

日期 是否一次通过 comment
2020-03-16 0

递归

public List<List<String>> partition(String str) {
        List<List<String>> res = new ArrayList<>();
        backtrack(res, new ArrayList<>(), str, 0);

        return res;
    }

    private void backtrack(List<List<String>> res, List<String> tempList, String str, int start){
        if(start == str.length()) {
            res.add(new ArrayList<>(tempList));
        } else {
            for(int i = start; i < str.length(); i++){
                if(isPalindrome(str, start, i)) {

                    tempList.add(str.substring(start, i + 1));  // 字符串范围[start, i+1)
                    backtrack(res, tempList, str, i + 1);
                    tempList.remove(tempList.size() - 1);
                }
            }
        }
    }


    private boolean isPalindrome(String s, int low, int high){
        while(low < high) {
            if (s.charAt(low++) != s.charAt(high--)) {
                return false;
            }
        }

        return true;
    }

相关文章

网友评论

      本文标题:131. Palindrome Partitioning

      本文链接:https://www.haomeiwen.com/subject/efmaehtx.html