131. 分割回文串

力扣链接:. - 力扣(LeetCode)

复制代码
class Solution {
    List<List<String>> ans = new ArrayList<>();
    List<String> temp = new ArrayList<>();
    String s;
    public List<List<String>> partition(String s) {
        this.s = s;
        dfs(0);
        return ans;
    }
    void dfs(int st) {
        if(st == s.length()) {
            ans.add(new ArrayList(temp));
            return ;
        }
        //注意,substring是左闭右开,所以是i<=s.length()
        for(int i=st+1;i<=s.length();i++) {
            String now = s.substring(st, i);
            if(check(now)) {
                temp.add(now);
                dfs(i);
                temp.remove(temp.size()-1);
            }
        }
    }

    boolean check(String str) {
        int len = str.length();
        for(int i=0;i<len/2+1;i++){
            if(str.charAt(i)!=str.charAt(len-i-1)){
                return false;
            }
        }
        return true;
    }
}
相关推荐
Darkwanderor7 小时前
什么数据量适合用什么算法
c++·算法
zc.ovo7 小时前
河北师范大学2026校赛题解(A,E,I)
c++·算法
py有趣7 小时前
力扣热门100题之环形链表
算法·leetcode·链表
py有趣8 小时前
力扣热门100题之回文链表
算法·leetcode·链表
月落归舟9 小时前
帮你从算法的角度来认识二叉树---(二)
算法·二叉树
SilentSlot10 小时前
【数据结构】Hash
数据结构·算法·哈希算法
样例过了就是过了11 小时前
LeetCode热题100 柱状图中最大的矩形
数据结构·c++·算法·leetcode
wsoz12 小时前
Leetcode哈希-day1
算法·leetcode·哈希算法
阿Y加油吧12 小时前
LeetCode 二叉搜索树双神题通关!有序数组转平衡 BST + 验证 BST,小白递归一把梭
java·算法·leetcode