Skip to content

Commit 7be4c4a

Browse files
Sean PrashadSean Prashad
authored andcommitted
Update 131_Palindrome_Partitioning.java
1 parent 809438f commit 7be4c4a

File tree

1 file changed

+13
-9
lines changed

1 file changed

+13
-9
lines changed

Backtracking/131_Palindrome_Partitioning.java

Lines changed: 13 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -5,30 +5,34 @@ public List<List<String>> partition(String s) {
55
}
66

77
List<List<String>> result = new ArrayList<>();
8-
dfs(0, s, new ArrayList<>(), result);
8+
helper(s, 0, result, new ArrayList<>());
9+
910
return result;
1011
}
1112

12-
private void dfs(int idx, String s, List<String> tempResult, List<List<String>> result) {
13+
private void helper(String s, int idx, List<List<String>> result, List<String> temp) {
1314
if (idx == s.length()) {
14-
result.add(new ArrayList<>(tempResult));
15+
result.add(new ArrayList<>(temp));
1516
return;
1617
}
1718

1819
for (int i = idx; i < s.length(); i++) {
1920
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);
21+
temp.add(s.substring(idx, i + 1));
22+
helper(s, i + 1, result, temp);
23+
temp.remove(temp.size() - 1);
2324
}
2425
}
2526
}
2627

27-
private boolean isPalindrome(String s, int start, int end) {
28-
while (start < end) {
29-
if (s.charAt(start++) != s.charAt(end--)) {
28+
private boolean isPalindrome(String s, int left, int right) {
29+
while (left < right) {
30+
if (s.charAt(left) != s.charAt(right)) {
3031
return false;
3132
}
33+
34+
++left;
35+
--right;
3236
}
3337

3438
return true;

0 commit comments

Comments
 (0)