Skip to content

Commit 6047570

Browse files
Sean PrashadSean Prashad
authored andcommitted
Add 131_Palindrome_Partitioning.java
1 parent a742036 commit 6047570

File tree

1 file changed

+36
-0
lines changed

1 file changed

+36
-0
lines changed
Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,36 @@
1+
class Solution {
2+
public List<List<String>> partition(String s) {
3+
if (s == null || s.length() == 0) {
4+
return Collections.emptyList();
5+
}
6+
7+
List<List<String>> result = new ArrayList<>();
8+
dfs(0, s, new ArrayList<>(), result);
9+
return result;
10+
}
11+
12+
private void dfs(int idx, String s, List<String> tempResult, List<List<String>> result) {
13+
if (idx == s.length()) {
14+
result.add(new ArrayList<>(tempResult));
15+
return;
16+
}
17+
18+
for (int i = idx; i < s.length(); i++) {
19+
if (isPalindrome(s, idx, i)) {
20+
tempResult.add(s.substring(idx, i + 1));
21+
dfs(i + 1, s, tempResult, result);
22+
tempResult.remove(tempResult.size() - 1);
23+
}
24+
}
25+
}
26+
27+
private boolean isPalindrome(String s, int start, int end) {
28+
while (start < end) {
29+
if (s.charAt(start++) != s.charAt(end--)) {
30+
return false;
31+
}
32+
}
33+
34+
return true;
35+
}
36+
}

0 commit comments

Comments
 (0)