zoukankan      html  css  js  c++  java
  • Palindrome Partitioning

    题目:

    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"]
      ]

    思路:这个题的解题思路和N-Queens那道题类似。最开始的时候,我们用一个循环列举出所有可能的开始状态。分别检查每一个状态是否满足题意。对于满足的开始状态,我们接着对其后续进行检查。

    每次检查的时候,1. 检查这个是不是终止状态。对于这道题,就是看我们是不是已经到达s的末尾了。2.如果不是,我们进入循环,对接下来每一个可能的状态进行检查。2.1 如果不符合题意,直接抛弃。2.2 如果符合,进行下一层的递归循环。

    感觉说的云里雾里的。。。直接看代码。。。

     1 public List<List<String>> partition(String s) {
     2         List<List<String>> ret = new ArrayList<List<String>>();
     3         if (s == null) {
     4             return ret;
     5         }
     6         ArrayList<String> path = new ArrayList<String>();
     7         dfs(s, 0, path, ret);
     8         return ret;
     9     }
    10     
    11     private static void dfs(String s, int index, ArrayList<String> path, List<List<String>> ret) {
    12         if (index == s.length()) {
    13             ret.add(new ArrayList<String>(path));
    14             return;
    15         }
    16         for (int i = index; i < s.length(); i++) {
    17             if (!isPalindrome(s.substring(index, i + 1))) {
    18                 continue;
    19             }
    20             path.add(s.substring(index, i + 1));
    21             dfs(s, i + 1, path, ret);
    22             path.remove(path.size() - 1);
    23         }
    24     }
    25     
    26     private static boolean isPalindrome(String s) {
    27         int left = 0;
    28         int right = s.length() - 1;
    29         while (left < right) {
    30             if (s.charAt(left) != s.charAt(right)) {
    31                 return false;
    32             }
    33             left++;
    34             right--;
    35         }
    36         return true;
    37     }



  • 相关阅读:
    vector读入指定行数但不指定列数的数字
    p4语言编程环境安装
    近期学习资料一览表
    c++之洛谷P1068分数线划定
    打开文件的方法
    调用当前年月日
    想学习启发式优化算法,不知从何学起?
    使用这几款插件,能让你在GitHub看代码的效率翻倍
    微信公众号放Latex数学公式的完美解决方案
    手把手教你用Git备份保存论文和代码等重要数据到云端
  • 原文地址:https://www.cnblogs.com/gonuts/p/4470154.html
Copyright © 2011-2022 走看看