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     }



  • 相关阅读:
    ajax
    文件下载--getOutputStream输出二进制字符
    文件上传功能实现代码
    java动态生成验证码
    项目中用到的jar包简介(2)
    python字符串的常见操作
    python切片使用方法(超详细)
    for循环结合range使用方法
    python使用while循环实现九九乘法表
    石家庄云修科技有限公司
  • 原文地址:https://www.cnblogs.com/gonuts/p/4470154.html
Copyright © 2011-2022 走看看