美文网首页
Leetcode 精选之搜索( 子集 II)

Leetcode 精选之搜索( 子集 II)

作者: Kevin_小飞象 | 来源:发表于2020-04-06 20:04 被阅读0次

    题目描述

    给定一个字符串 s,将 s 分割成一些子串,使每个子串都是回文串。

    返回 s 所有可能的分割方案。

    示例:

    输入: "aab"
    输出:
    [
    ["aa","b"],
    ["a","a","b"]
    ]

    题目链接:力扣

    解题思路

    class Solution {
       public List<List<String>> partition(String s) {
            List<List<String>> partitions = new ArrayList<>();
            List<String> tempPartition = new ArrayList<>();
            doPartition(s, partitions, tempPartition);
            return partitions;
        }
    
        private void doPartition(String s, List<List<String>> partitions, List<String> tempPartition) {
            if (s.length() == 0) {
                partitions.add(new ArrayList<>(tempPartition));
                return;
            }
            for (int i = 0; i < s.length(); i++) {
                if (isPalindrome(s, 0, i)) {
                    tempPartition.add(s.substring(0, i + 1));
                    doPartition(s.substring(i + 1), partitions, tempPartition);
                    tempPartition.remove(tempPartition.size() - 1);
                }
            }
        }
    
        private boolean isPalindrome(String s, int begin, int end) {
            while (begin < end) {
                if (s.charAt(begin++) != s.charAt(end--)) {
                    return false;
                }
            }
            return true;
        }
    }
    

    测试结果

    image.png

    相关文章

      网友评论

          本文标题:Leetcode 精选之搜索( 子集 II)

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