[leetcode]131. 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.

Example:

Input: "aab"
Output:
[
  ["aa","b"],
  ["a","a","b"]
]

题意:

拆分给定字符串,找到可将字符串分隔成回文substring的可能

思路:

backtracking枚举所有结果

容易掉坑:对于递归调用helper的时候,i+1 还是index+1 很容易就写错了!!!

代码:

 1 class Solution {
 2     public List<List<String>> partition(String s) {
 3         List<List<String>> result = new ArrayList<>();
 4         List<String> path = new ArrayList<>();
 5         helper(s, 0, path, result);
 6         return result;
 7     }
 8     
 9     private void helper(String s, int index, List<String> path,List<List<String>> result){
10         if( index == s.length()){
11             result.add(new ArrayList<>(path));
12         }
13         for(int i = index ; i < s.length() ; i++){
14             if(isPalindrome(s, index, i)){ // 如果index--i 的这段串串是回文
15                 path.add(s.substring(index, i+1));// 将index--i 的这段回文串串加到path里
16                 helper(s, i+1, path, result); // 继续移动index递归生成可能的结果
17                 path.remove(path.size() -1); //比如"baa" 从root 为'b'开始则先生成Arraylist : 'b' + 'a' + 'a' 则要去掉最后一个元素'a'
18                                            // 再看 'b' + 'a' + '其他'  能新生成Arraylist                                              
19             }
20         }
21     }
22     // 判断是否回文      
23     private boolean isPalindrome(String s, int left, int right){
24         while (left < right){
25             if(s.charAt(left) != s.charAt(right)){
26                 return false;
27             }
28             left++;
29             right--;
30         }
31       return true;
32     }
33 }
原文地址:https://www.cnblogs.com/liuliu5151/p/9075033.html