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

    分割回文串

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

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

    示例:

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

    解题思路:首先创建一个数组记录i到j是否为回文,之后用dfs进行回溯

    class Solution {
        public List<List<String>> partition(String s) {
            if(s == null)
                return null;
            
            List<List<String>> ans = new ArrayList();
            
            if(s.isEmpty())
                return ans;
            
            char[] ch = s.toCharArray();
            int len = ch.length;
            boolean isPail[][] = new boolean[len][len];
            
            for(int i = 0; i < len; i++) {
                for(int j = 0; j <= i; j++) {
                    isPail[j][i] = check(ch, j, i);
                    // System.out.println("i = " + j + ", j = " + i + ", dp = " + isPail[j][i]);
                }
            }
                    
            Deque<String> list = new LinkedList();
            dfs(0, len, list, isPail, ans, s);
            
            return ans;
        }
        
        private void dfs(int start, int len, Deque<String> path, boolean[][] dp, List<List<String>> res, String s) {
            if (start == len) {
                res.add(new ArrayList<>(path));
                return;
            }
    
            for (int i = start; i < len; i++) {
                if (!dp[start][i]) {
                    continue;
                }
                path.addLast(s.substring(start, i + 1));
                dfs(i + 1, len, path, dp, res, s);
                path.removeLast();
            }
        }
        
        private boolean check(char[] ch, int i, int j) {
            while(i < j && ch[i] == ch[j]) {
                i++;
                j--;
            }
            
            return i >= j;
        }
    }
    
  • 相关阅读:
    python excel导入到数据库
    ubuntu14.04修改mysql默认编码
    python 向MySQL里插入中文数据
    hbase框架原理
    hive框架原理
    Hadoop的MapReduce模型基本原理
    机器学习模型效果评价
    spark架构原理
    Hadoop架构原理
    特征工程
  • 原文地址:https://www.cnblogs.com/katoMegumi/p/14025795.html
Copyright © 2011-2022 走看看