• 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.

  • 相关阅读:
    【POJ 2778】DNA Sequence
    【POJ 2923】Relocation
    codeforces 475D
    hdu4742
    hdu4741
    hdu5016
    poj3929
    Codeforces Round #267 (Div. 2)
    codeforces 455E
    hdu4073 Lights
  • 原文地址:https://www.cnblogs.com/Dylan-Java-NYC/p/4824962.html
Copyright © 2020-2023  润新知