LeetCode131-分割字符串

题目链接

英文链接:https://leetcode.com/problems/palindrome-partitioning/

中文链接:https://leetcode-cn.com/problems/palindrome-partitioning/

题目详述

给定一个字符串 s,将 s 分割成一些子串,使每个子串都是回文串。

返回 s 所有可能的分割方案。

示例:

1
2
3
4
5
6
输入: "aab"
输出:
[
["aa","b"],
["a","a","b"]
]

题目详解

DFS,回溯。

  • 首先截取字符串的前一部分。
  • 如果这一部分是回文串则递归进入下一层,否则重新截取。
  • 进入下一层前加入临时集合,退出时进行恢复。
  • 递归的终止条件是最终传入的字符串长度为 0。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
public class LeetCode_00131 {

public List<List<String>> partition(String s) {
List<List<String>> res = new ArrayList<>();
List<String> list = new ArrayList<>();
dfs(s, res, list);
return res;
}

private void dfs(String s, List<List<String>> res, List<String> list) {
if (s.length() == 0) {
res.add(new ArrayList<>(list));
return;
}
for (int i = 1; i <= s.length(); ++i) {
String sub = s.substring(0, i);
if (isPalindrome(sub)) {
list.add(sub);
dfs(s.substring(i), res, list);
list.remove(list.size() - 1);
}
}
}

private boolean isPalindrome(String s) {
int i = 0;
int j = s.length() - 1;
while (i < j) {
if (s.charAt(i++) != s.charAt(j--)) {
return false;
}
}
return true;
}
}