zoukankan      html  css  js  c++  java
  • Backtracking_131. 分割回文串

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

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

    示例:

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

    来源:力扣(LeetCode)
    链接:https://leetcode-cn.com/problems/palindrome-partitioning


    思路:

    DFS的回溯算法,如果字符串的分段是回文的就截取片段判断后面的

    如果到最后字符串已经被分解的只剩下0的长度,说明就是我们想要的部分,保存到res中

    class Solution {
        public List<List<String>> partition(String s){
            List<List<String>> res = new LinkedList<>();
            List<String> path = new ArrayList<>();
            dfs(path,res,s);
            return res;
        }
    
        private void dfs(List<String> path, List<List<String>> res, String s) {
            if (s.length() == 0){
                res.add(new ArrayList<>(path));
                return;
            }
            for (int i = 0; i < s.length(); i++) {
                if (isPalindrome(s,0,i)){
                    path.add(s.substring(0,i + 1));
                    dfs(path,res,s.substring(i + 1));
                    path.remove(path.size() - 1);
                }
            }
        }
    
        //判断是否回文
        public boolean isPalindrome(String s,int begin,int end){
            while (begin < end){
                if (s.charAt(begin) == s.charAt(end)){
                    begin++;
                    end--;
                }else {
                    return false;
                }
            }
            return true;
        }
    }
  • 相关阅读:
    MySQL-02 数据表管理
    MySQL-01 MySQL数据库安装指南
    Linux-04 Linux中Tomcat和MySQL的安装
    Linux-03 Linux下的tar命令
    Linux-02 Linux常用命令
    Linux-01 虚拟机Linux的安装
    从服务器下载图片
    WPF Radio组的绑定
    使用缓存的9大误区(下)转载
    使用缓存的9大误区(上)转载
  • 原文地址:https://www.cnblogs.com/zzxisgod/p/13376576.html
Copyright © 2011-2022 走看看