• 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
  • 相关阅读:
    平衡二叉树(AVL Tree)
    算法分析
    稳定匹配
    Python读取不同文件夹下的图片并且分类放到新创建的训练文件夹和标签文件夹
    java构造函数也可以用private开头
    基于slf4j的log4j实战
    javascript权威指南第6版学习笔记
    hadoop之wordCount程序理解
    java 基本类型和包装类的比较
    设计模式之工厂模式,单例模式,门面模式
  • 原文地址:https://www.cnblogs.com/cing/p/8796009.html
Copyright © 2020-2023  润新知