zoukankan      html  css  js  c++  java
  • Palindrome Partitioning——LeetCode

    Given a string s, partition s such that every substring of the partition is a palindrome.

    Return all possible palindrome partitioning of s.

    For example, given s = "aab",
    Return

      [
        ["aa","b"],
        ["a","a","b"]
      ]
    

    题目大意:给一个字符串,输出这个字符串所有可能的回文子串。

    解题思路:这道题我是用回溯来解,dfs之后再还原状态,首先确定解由两部分构成,每次只拆分后半部分,验证前半部分,如果前面是回文,则递归拆分并验证后半部分。

    注意:DFS之后要还原状态,从上一个合法解之后继续遍历其他可能。

    Talk is cheap>>

    public class PalindromePartitioning {
        public List<List<String>> partition(String s) {
            List<List<String>> res = new ArrayList<>();
            ArrayList<String> tmp = new ArrayList<>();
            int length = s.length();
            dfs(s, tmp, res, length);
            return res;
        }
    
        public void dfs(String src, ArrayList<String> tmp, List<List<String>> res, int length) {
            if (length == 0) {
                res.add((ArrayList<String>) tmp.clone());
                return;
            }
            for (int i = 1; i <= src.length(); i++) {
                if (isValid(src.substring(0, i))) {
                    tmp.add(src.substring(0, i));
                    dfs(src.substring(i, src.length()), tmp, res, length - i);
                    tmp.remove(tmp.size() - 1);
                }
            }
        }
    
        public boolean isValid(String s) {
            if (s == null || s.length() <= 1) {
                return true;
            }
            int i = 0, j = s.length() - 1;
            while (i < j) {
                if (s.charAt(i) != s.charAt(j)) {
                    return false;
                }
                i++;
                j--;
            }
            return true;
        }
    }
     
  • 相关阅读:
    JavaScript 中正则匹配时结果不一致的问题
    /dev/null
    Xcode 中通过 target 运行多个 c 程序
    Xcode 调试时打印变量值
    Recoil 请求的刷新之使用随机参数
    npm ci 与 install 的区别
    项目中私有 npm 源的设置
    Crontab 的使用
    Nest 在日志中打印对象
    配置 ESLint 自动格式化自闭合标签(Self closing tag)
  • 原文地址:https://www.cnblogs.com/aboutblank/p/4394179.html
Copyright © 2011-2022 走看看