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     }


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM