• 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     }



  • 相关阅读:
    readonly const
    多线程的安全性
    【C++】operator运算符重载
    C++ 多态的实现及原理(转载)
    C语言宽字符处理函数对照表
    UTF8编码规则(转)
    PE文件结构(转)
    C语言中宏定义
    汇编语言移位指令
    数组指针应该结合二维数组多维数组来理解
  • 原文地址:https://www.cnblogs.com/gonuts/p/4470154.html
Copyright © 2020-2023  润新知