zoukankan      html  css  js  c++  java
  • Palindrome Partitioning leetcode java

    题目

    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"]
      ]
    

    题解

    这道题还是一种找组合的可能性,类似于wordbreakii。
    这里想法是,用递归循环找子问题的方法,把母串按所有组合可能性拆分,如果是回文,就加进来,当层数为s的length时就有一个结果了。
    这里需要判断是否为回文。
    利用validPalindrome的思想很容易就写出来了(这里不需要判断大小写还有有没有别的字符)。

    代码如下:
     1     public ArrayList<ArrayList<String>> partition(String s) {
     2         ArrayList<String> item = new ArrayList<String>();
     3         ArrayList<ArrayList<String>> res = new ArrayList<ArrayList<String>>();
     4         
     5         if(s==null||s.length()==0)
     6             return res;
     7         
     8         dfs(s,0,item,res);
     9         return res;
    10     }
    11     
    12     public void dfs(String s, int start, ArrayList<String> item, ArrayList<ArrayList<String>> res){
    13         if (start == s.length()){
    14             res.add(new ArrayList<String>(item));
    15             return;
    16         }
    17         
    18         for (int i = start; i < s.length(); i++) {
    19             String str = s.substring(start, i+1);
    20             if (isPalindrome(str)) {
    21                 item.add(str);
    22                 dfs(s, i+1, item, res);
    23                 item.remove(item.size() - 1);
    24             }
    25         }
    26     }
    27     
    28     
    29     public boolean isPalindrome(String s){
    30          int low = 0;
    31          int high = s.length()-1;
    32          while(low < high){
    33              if(s.charAt(low) != s.charAt(high))
    34                 return false;
    35              low++;
    36              high--;
    37          }
    38          return true;
    39     }

  • 相关阅读:
    RedHat 更新CentOS Yum源(转)
    ubuntu 印象笔记
    (转)FFMPEG filter使用实例(实现视频缩放,裁剪,水印等)
    (转)学习ffmpeg官方示例transcoding.c遇到的问题和解决方法
    源码调用ffmpeg库时,需要注意接口为C接口
    codeforces 722D Generating Sets 【优先队列】
    poj2970 The lazy programmer 【优先队列】
    codeblocks17.12 不能启动调试器
    Unity动画知识之二:Animator动画状态机
    关于unity里pbr技术和材质 unity5默认shader和传统的对比
  • 原文地址:https://www.cnblogs.com/springfor/p/3884197.html
Copyright © 2011-2022 走看看