Star

LeetCode 131.Palindrome Partitioning

Question

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

1
2
3
4
5
[
["aa","b"],
["a","a","b"]
]

Explanation

用回溯法找到每种可能的组合的模式,然后对于每个部分字符串去判断是否是回文字符串。算是常规题,略组合了一下,有趣。

Code

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
public class Solution {
public List<List<String>> partition(String s) {
List<List<String>> result = new ArrayList<>();
if (s == null || s.length() == 0) return result;
List<String> patition = new ArrayList<>();
helper(s, 0, patition, result);
return result;
}
public void helper(String s, int index, List<String> partition, List<List<String>> result) {
if (index == s.length()) {
result.add(new ArrayList<String>(partition));
}
for (int i=index; i<s.length(); i++) {
String subString = s.substring(index, i+1);
if (!isPalindrome(subString)) continue;
partition.add(subString);
helper(s, i+1, partition, result);
partition.remove(partition.size()-1);
}
}
//check for palindrome
public boolean isPalindrome(String s) {
if (s == null || s.length() == 0) return true;
int i=0; int j = s.length() -1 ;
s = s.toLowerCase();
while (i < j) {
if (!Character.isLetterOrDigit(s.charAt(i))) {
i ++;
} else if (!Character.isLetterOrDigit(s.charAt(j))) {
j--;
} else if (s.charAt(i)!=s.charAt(j)) {
return false;
} else {
i++; j--;
}
}
return true;
}
}