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;
    }
}
相关推荐
MediaTea5 小时前
AI 术语通俗词典:C4.5 算法
人工智能·算法
Navigator_Z5 小时前
LeetCode //C - 1033. Moving Stones Until Consecutive
c语言·算法·leetcode
WBluuue5 小时前
数据结构与算法:莫队(一):普通莫队与带修莫队
c++·算法
风筝在晴天搁浅6 小时前
n个六面的骰子,扔一次之后和为k的概率是多少?
算法
MATLAB代码顾问7 小时前
Python实现蜂群算法优化TSP问题
开发语言·python·算法
代码飞天7 小时前
机器学习算法和函数整理——助力快速查阅
人工智能·算法·机器学习
jiushiapwojdap7 小时前
LU分解法求解线性方程组Matlab实现
数据结构·其他·算法·matlab
笨笨饿7 小时前
69_如何给自己手搓一个串口
linux·c语言·网络·单片机·嵌入式硬件·算法·个人开发
纽扣6678 小时前
【算法进阶之路】链表进阶:删除、合并、回文与排序全解析
数据结构·算法·链表
消失的旧时光-19438 小时前
统一并发模型:线程、Reactor、协程本质是一件事(从线程到协程 · 第6篇·终章)
java·python·算法