美文网首页快乐写代码
T131、分割回文串

T131、分割回文串

作者: 上行彩虹人 | 来源:发表于2020-10-02 16:18 被阅读0次

给定一个字符串 s,将 s 分割成一些子串,使每个子串都是回文串。
返回 s 所有可能的分割方案。
示例:
输入: "aab"
输出:
[
["aa","b"],
["a","a","b"]
]

回溯求解。从前向后依次遍历字符串,然后判断每次划分结果是否是回文串,如果不是则跳过本次回溯。

 public List<List<String>> partition(String s) {
        List<List<String>> res = new ArrayList<>();
        int len = s.length();
        if(len <= 0)
            return res;
        Deque<String> stack = new ArrayDeque<>();
        backtrace(s,0,s.length(),stack,res);
        return res;
    }
    
    public void backtrace(String s, int start, int len, Deque<String> path, List<List<String>> res){
        if(start == len){
            res.add(new ArrayList<>(path));
            return;
        }
        for(int i = start; i < len; i++){
            if(!check(s,start,i))
                continue;
            path.addLast(s.substring(start,i+1));
            backtrace(s,i+1,len,path,res);
            path.removeLast();
        }
    }
    public boolean check(String s, int l, int r){
        while(l < r){
            if(s.charAt(l) != s.charAt(r))
                return false;
            l++;
            r--;
        }
        return true;
    }

相关文章

  • T131、分割回文串

    给定一个字符串 s,将 s 分割成一些子串,使每个子串都是回文串。返回 s 所有可能的分割方案。示例:输入: "a...

  • LeetCode-131-分割回文串

    LeetCode-131-分割回文串 131. 分割回文串[https://leetcode-cn.com/pro...

  • lintcode-分割回文串

    给定一个字符串s,将s分割成一些子串,使每个子串都是回文串。 返回s所有可能的回文串分割方案。

  • 131. 分割回文串

    给你一个字符串 s,请你将 s 分割成一些子串,使每个子串都是 回文串 。返回 s 所有可能的分割方案。 回文串 ...

  • LeetCode-131-分割回文串

    分割回文串 题目描述:给你一个字符串 s,请你将 s 分割成一些子串,使每个子串都是 回文串 。返回 s 所有可能...

  • LeetCode 131. 分割回文串

    题目 给你一个字符串 s,请你将 s 分割成一些子串,使每个子串都是 回文串 。返回 s 所有可能的分割方案。回文...

  • leetcode131 分割回文串

    题目 分割回文串 分析 简单dfs问题,关键点在于如何快速的判断回文串。这里我们就可以预先找出所有的回文串,再每次...

  • LeetCode 131 [Palindrome Partiti

    原题 给定一个字符串s,将s分割成一些子串,使每个子串都是回文串。返回s所有可能的回文串分割方案。 样例给出 s ...

  • LeetCode #1278 Palindrome Partit

    1278 Palindrome Partitioning III 分割回文串 III Description: Y...

  • 108. 分割回文串 II

    描述 给定字符串 s, 需要将它分割成一些子串, 使得每个子串都是回文串. 最少需要分割几次? 样例 思路: 考虑...

网友评论

    本文标题:T131、分割回文串

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