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;
        }
    }
     
  • 相关阅读:
    Macbook键盘的使用基础技巧
    JSTL详解
    为了理想,因为爱情-开课第一天有感(鸡汤向)
    HK游记 Day2迪斯尼(下)
    MP20 MBO issue summary
    音频测量加权
    有没有降噪
    信源编码信源译码和信道编码和译码和加密和解密数字调制和解调和同步
    gcc
    数据挖掘|统计的艺术
  • 原文地址:https://www.cnblogs.com/aboutblank/p/4394179.html
Copyright © 2011-2022 走看看