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
  • 相关阅读:
    nth_element 使用方法
    Codeforces-1326E Bombs
    GDB下调试查看数组部分内容
    0930,主外键设置
    0928,数据库
    0924,函数返回多个值
    0921,函数 枚举
    0920,结构体
    0918,练习题
    0916,双色球练习题
  • 原文地址:https://www.cnblogs.com/cing/p/8796009.html
Copyright © 2011-2022 走看看