Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
Skip to content

Commit 0119905

Browse files
add a solution for 131
1 parent 432187a commit 0119905

File tree

1 file changed

+34
-0
lines changed
  • src/main/java/com/fishercoder/solutions

1 file changed

+34
-0
lines changed

src/main/java/com/fishercoder/solutions/_131.java

Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,40 @@
66
public class _131 {
77

88
public static class Solution1 {
9+
/**
10+
* credit: https://leetcode.com/problems/palindrome-partitioning/solution/
11+
* DFS + backtracking
12+
*/
13+
public List<List<String>> partition(String s) {
14+
List<List<String>> result = new ArrayList<>();
15+
dfs(0, result, new ArrayList<>(), s);
16+
return result;
17+
}
18+
19+
private void dfs(int start, List<List<String>> result, List<String> currentList, String s) {
20+
if (start >= s.length()) {
21+
result.add(new ArrayList<>(currentList));
22+
}
23+
for (int end = start; end < s.length(); end++) {
24+
if (isPalindrome(s, start, end)) {
25+
currentList.add(s.substring(start, end + 1));
26+
dfs(end + 1, result, currentList, s);
27+
currentList.remove(currentList.size() - 1);
28+
}
29+
}
30+
}
31+
32+
private boolean isPalindrome(String s, int start, int end) {
33+
while (start < end) {
34+
if (s.charAt(start++) != s.charAt(end--)) {
35+
return false;
36+
}
37+
}
38+
return true;
39+
}
40+
}
41+
42+
public static class Solution2 {
943
public List<List<String>> partition(String s) {
1044
List<List<String>> result = new ArrayList();
1145
int n = s.length();

0 commit comments

Comments
 (0)