0%

Leetcode131-palindromePartitioning

Description

Given a string s, partition s such that every substring of the partition is a palindrome.

Return all possible palindrome partitioning of s.

Example

1
2
3
4
5
6
Input: "aab"
Output:
[
["aa","b"],
["a","a","b"]
]

Solution

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
class Solution {
public List<List<String>> partition(String s) {
List<List<String>> res = new ArrayList<>();
if (s.length() == 0){
res.add(new ArrayList<>());
return res;
}
helper(res, s, new ArrayList<String>(), 0);
return res;
}
private void helper(List<List<String>> res, String s, List<String> temp, int index){
if (index > s.length()-1){
res.add(new ArrayList<>(temp));
}
for (int i = index + 1; i <= s.length(); i++){
String cur = s.substring(index, i);
if (!isPalindrome(cur)) continue;
temp.add(cur);
helper(res, s, temp, i);
temp.remove(temp.size()-1);
}
}
private boolean isPalindrome(String s){
int left = 0;
int right = s.length()-1;
while(left < right){
if (s.charAt(left) != s.charAt(right)) return false;
left ++;
right --;
}
return true;
}
}