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

    原题链接在这里:https://leetcode.com/problems/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"]
    ]

    题解:

    backtracking问题, dfs时当前一段如果是Palindrome就加进item. 然后递归调用helper, 递归终止条件是能正好走到s.length().

    Time Complexity: exponential. 

    Space: O(res.size()).

    AC Java:

     1 public class Solution {
     2     public List<List<String>> partition(String s) {
     3         List<List<String>> res = new ArrayList<List<String>>();
     4         if(s == null || s.length() == 0){
     5             return res;
     6         }
     7         helper(s,0, new ArrayList<String>(),res);  
     8         return res;
     9     }
    10     private void helper(String s, int start,List<String> item, List<List<String>> res){
    11         if(start == s.length()){
    12             res.add(new ArrayList(item));
    13             return;
    14         }
    15         StringBuilder sb = new StringBuilder();
    16         for(int i = start; i <s.length(); i++){
    17             sb.append(s.charAt(i));
    18             if(isPalindrome(sb.toString())){
    19                 item.add(sb.toString());
    20                 helper(s,i+1,item,res);
    21                 item.remove(item.size()-1);
    22             }
    23         }
    24     }
    25     private boolean isPalindrome(String s){
    26         if(s == null || s.length() == 0){
    27             return true;
    28         }
    29         int i = 0;
    30         int j = s.length()-1;
    31         while(i<j){
    32             if(s.charAt(i) != s.charAt(j)){
    33                 return false;
    34             }
    35             i++;
    36             j--;
    37         }
    38         return true;
    39     }
    40 }

    类似Word Break IISubsets.

    跟上Palindrome Partitioning II.

  • 相关阅读:
    Java calendar类学习笔记
    Anaconda 学习笔记
    第八周作业
    第七次作业
    第六周作业
    第五次作业
    用户调研方法之焦点小组
    第三周作业
    软件工作量的评估方法有哪些
    软件质量保证与测试(--作业--)
  • 原文地址:https://www.cnblogs.com/Dylan-Java-NYC/p/4824962.html
Copyright © 2011-2022 走看看