Leetcode每日一题(分割回文串Ⅰ)

分割回文串Ⅰ 

import java.util.ArrayList;
import java.util.List;

class Solution {
    private List<List<String>> ans = new ArrayList<>();
    boolean f[][] = new boolean[1010][1010];//i到j的字符是否为回文串

    public  static void main(String[] args) {
        System.out.println(new Solution().partition("bbab"));
    }
    public void dfs(String s, int u, List<String> path) {//从0到u所有子串
        if (u == s.length()) {//如果一次遍历完成,返回路径
            ans.add(new ArrayList<>(path));
        } else {
            for (int i = u; i < s.length(); i++) {//从当前下标寻找回文串
                if (f[i][u] == true) {//i到u是否为回文串
                    path.add(s.substring(u, i + 1));
                    dfs(s, i + 1, path);
                    path.remove(path.size() - 1);
                }
            }
        }
    }

    public List<List<String>> partition(String s) {
        for (int i = 0; i < s.length(); i++) {
            for (int j = 0; j <= i; j++) {
                if (i == j) f[i][j] = true;//如果是一个字符时 是回文串
                else if (s.charAt(i) == s.charAt(j)) {//当两个字符相等
                    //1,当前字符串长度为2 2,当前字符串除了首尾的字符的子字符串为回文串
                    if (i == j + 1 || f[i - 1][j + 1] == true) {
                        f[i][j] = true;
                    }
                }
            }
        }
        dfs(s, 0, new ArrayList<>());//从下标为u开始的回文串
        return ans;
    }
}

 

相关推荐

  1. 每日OJ_dp④_力扣132. 分割 II

    2023-12-15 17:16:03       41 阅读
  2. leetcodeHOT leetcode131. 分割

    2023-12-15 17:16:03       47 阅读
  3. LeetCode-热100:131. 分割

    2023-12-15 17:16:03       47 阅读
  4. leetcode 131. 分割

    2023-12-15 17:16:03       57 阅读

最近更新

  1. docker php8.1+nginx base 镜像 dockerfile 配置

    2023-12-15 17:16:03       98 阅读
  2. Could not load dynamic library ‘cudart64_100.dll‘

    2023-12-15 17:16:03       106 阅读
  3. 在Django里面运行非项目文件

    2023-12-15 17:16:03       87 阅读
  4. Python语言-面向对象

    2023-12-15 17:16:03       96 阅读

热门阅读

  1. 数据结构 | 二叉树交换左右子树

    2023-12-15 17:16:03       68 阅读
  2. 软件编程规范

    2023-12-15 17:16:03       60 阅读
  3. latex 中使用listings超行后显示弧线

    2023-12-15 17:16:03       49 阅读
  4. 机器学习——数据清洗

    2023-12-15 17:16:03       44 阅读
  5. oracle 修改监听端口

    2023-12-15 17:16:03       54 阅读
  6. GPIO复用时5个调试接口引脚要注意

    2023-12-15 17:16:03       69 阅读
  7. docker搭建gitlab

    2023-12-15 17:16:03       68 阅读
  8. nestjs上传文件

    2023-12-15 17:16:03       66 阅读
  9. 【前端设计模式】之命令模式

    2023-12-15 17:16:03       66 阅读
  10. GoLang EASY 游戏框架 之 应用项目+教程 02

    2023-12-15 17:16:03       58 阅读
  11. 深入Rust的模式匹配与枚举类型

    2023-12-15 17:16:03       54 阅读
  12. 【Python】多维列表排序

    2023-12-15 17:16:03       60 阅读