2024/9/11 LeetCode Hot100 backtracking 昨日leetcode
This commit is contained in:
parent
ecf2f98b85
commit
ca680d7b82
|
@ -0,0 +1,52 @@
|
|||
package com.cool.hot100.backtracking;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
|
||||
/**
|
||||
* Created with IntelliJ IDEA.
|
||||
*
|
||||
* @Author: Cool
|
||||
* @Date: 2024/09/11/23:12
|
||||
* DayNumber 2
|
||||
* Hard 2
|
||||
* Level 5
|
||||
*/
|
||||
public class Num131 {
|
||||
|
||||
|
||||
private List<List<String>> res = new ArrayList<>();
|
||||
private List<String> list = new ArrayList<>();
|
||||
private String str;
|
||||
|
||||
public List<List<String>> partition(String s) {
|
||||
str = s;
|
||||
dfs(0, 0);
|
||||
return res;
|
||||
}
|
||||
|
||||
private void dfs(int i, int start) {
|
||||
if (i == str.length()) {
|
||||
res.add(new ArrayList<>(list));
|
||||
return;
|
||||
}
|
||||
if (i < str.length() - 1) {
|
||||
dfs(i + 1, start);
|
||||
}
|
||||
if (isPalindrome(start, i)) {
|
||||
list.add(str.substring(start, i + 1));
|
||||
dfs(i + 1, i + 1);
|
||||
list.remove(list.size() - 1);
|
||||
}
|
||||
}
|
||||
|
||||
private boolean isPalindrome(int left, int right) {
|
||||
while (left < right) {
|
||||
if (str.charAt(left++) != str.charAt(right--)) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
}
|
Loading…
Reference in New Issue