public class DayCode {
public static void main(String[] args) {
String s = "aab";
List ans = new DayCode().partition(s);
System.out.println("ans is " + ans.toString());
}
/**
* https://leetcode-cn.com/problems/palindrome-partitioning/
* @param s
* @return
*/
public List<List<String>> partition(String s) {
List<List<String>> ans = new ArrayList<>();
int len = s.length();
if (len == 0) {
return ans;
}
Deque<String> stack = new ArrayDeque<>();
char[] charArray = s.toCharArray();
dfs(charArray, 0, len, stack, ans);
return ans;
}
/**
* 子串
*
* @param charArray
* @param index
* @param len
* @param path
* @param ans
*/
private void dfs(char[] charArray, int index, int len, Deque<String> path, List<List<String>> ans) {
if (index == len) {
ans.add(new ArrayList<>(path));
return;
}
for (int i = index; i < len; i++) {
if (!checkPalindrome(charArray, index, i)) {
continue;
}
path.addLast(new String(charArray, index, i + 1 - index));
dfs(charArray, i + 1, len, path, ans);
path.removeLast();
}
}
/**
* 验证回文串
*
* @param charArray
* @param left
* @param right
* @return
*/
private boolean checkPalindrome(char[] charArray, int left, int right) {
while (left < right) {
if (charArray[left] != charArray[right]) {
return false;
}
left++;
right--;
}
return true;
}
}
评论