kniost

谁怕,一蓑烟雨任平生

0%

LeetCode 131. Palindrome Partitioning

131. Palindrome Partitioning

Difficulty:: Medium

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

Language: Java

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
class Solution {
public List<List<String>> partition(String s) {
List<List<String>> result = new ArrayList<>();
if (s == null || s.length() == 0) {
return result;
}
dfsHelper(s, 0, result, new ArrayList<String>());
return result;
}

private void dfsHelper(String s, int start,
List<List<String>> result, List<String> partition) {
if (start == s.length()) {
result.add(new ArrayList<>(partition));
}
for (int i = start; i < s.length(); i++) {
if (isPalindrome(s, start, i)) {
partition.add(s.substring(start, i + 1));
dfsHelper(s, i + 1, result, partition);
partition.remove(partition.size() - 1);
}
}
}

// [start, end]
private boolean isPalindrome(String s, int start, int end) {
while (start < end) {
if (s.charAt(start++) != s.charAt(end--)) {
return false;
}
}
return true;
}
}