zoukankan      html  css  js  c++  java
  • 131.Palindrome Partitioning

    题目链接

    题目大意:给出一个字符串,将其划分,使每个子串都是回文串,计算处所有可能的划分情况。

    法一(借鉴):很明显的,是要用DFS。这个可以作为一个模板吧,就是划分字符串的所有子串的一个模板。代码如下(耗时9ms):

     1     public List<List<String>> partition(String s) {
     2         List<List<String>> res = new ArrayList<List<String>>();
     3         List<String> tmp = new ArrayList<String>();
     4         dfs(s, res, 0, tmp);
     5         return res;
     6     }
     7     private static void dfs(String s, List<List<String>> res, int start, List<String> tmp) {
     8         //如果找到一种划分情况,则将其接入结果集中
     9         if(start == s.length()) {
    10             res.add(new ArrayList<String>(tmp));
    11             return;
    12         }
    13         //寻找每一个可能的回文字符串
    14         for(int i = start; i < s.length(); i++) {
    15             //判断字符串的其中一个子串,如果是回文
    16             if(isPalindrome(s, start, i) == true) {
    17                 //将这个回文子串加入结果中,记住substring(start,end),是从start到end-1的字符串。
    18                 tmp.add(s.substring(start, i + 1));
    19                 //注意,下次划分的子串起始点应该是i+1,因为i已经在上一个子串中了
    20                 dfs(s, res, i + 1, tmp);
    21                 //回溯移除
    22                 tmp.remove(tmp.size() - 1);
    23             }
    24         }
    25     }
    26     //判断回文
    27     private static boolean isPalindrome(String s, int start, int end) {
    28         while(start <= end) {
    29             if(s.charAt(start) != s.charAt(end)) {
    30                 return false;
    31             }
    32             start++;
    33             end--;
    34         }
    35         return true;
    36     }
    View Code
  • 相关阅读:
    List遍历时删除与迭代器(Iterator)解惑
    从一次“并发修改字段业务”引出多版本并发控制与InnoDB锁
    RocketMQ存储机制与确认重传机制
    Java中的锁
    jmeter在non-GUI模式下用法
    Java SPI机制简述
    深拷贝、浅拷贝与Cloneable接口
    Java中的小数运算与精度损失
    java中的枚举类
    SpringBoot是如何实现自动配置的
  • 原文地址:https://www.cnblogs.com/cing/p/8796009.html
Copyright © 2011-2022 走看看