题目
法1:DFS+双指针
必须掌握基础方法!
注意:使用ArrayList删除尾元素比LinkedList要快很多!!!
class Solution {
public List<List<String>> partition(String s) {
List<List<String>> res = new ArrayList<>();
if (s.length() == 0) {
return res;
}
List<String> tmp = new ArrayList<>();
dfs(s, 0, tmp, res);
return res;
}
public void dfs(String s, int startIndex, List<String> tmp, List<List<String>> res) {
if (startIndex == s.length()) {
res.add(new ArrayList<>(tmp));
return;
}
for (int i = startIndex; i < s.length(); ++i) {
if (!valid(s, startIndex, i)) {
continue;
}
tmp.add(s.substring(startIndex, i + 1));
dfs(s, i + 1, tmp, res);
tmp.remove(tmp.size() - 1);
}
}
public boolean valid(String s, int startIndex, int endIndex) {
while (startIndex <= endIndex) {
char left = s.charAt(startIndex);
char right = s.charAt(endIndex);
if (left != right) {
return false;
}
++startIndex;
--endIndex;
}
return true;
}
}
法2:DFS+回文串判断预处理
主要优化回文串判断部分
class Solution {
public List<List<String>> partition(String s) {
List<List<String>> res = new ArrayList<>();
int n = s.length();
if (n == 0) {
return res;
}
boolean[][] valid = new boolean[n][n];
List<String> tmp = new ArrayList<>();
for (int i = 0; i < n; ++i) {
Arrays.fill(valid[i], true);
}
for (int i = n - 1; i >= 0; --i) {
for (int j = i + 1; j < n; ++j) {
valid[i][j] = (s.charAt(i) == s.charAt(j)) && valid[i + 1][j - 1];
}
}
dfs(s, 0, tmp, res, valid);
return res;
}
public void dfs(String s, int startIndex, List<String> tmp, List<List<String>> res, boolean[][] valid) {
if (startIndex == s.length()) {
res.add(new ArrayList<>(tmp));
return;
}
for (int i = startIndex; i < s.length(); ++i) {
if (valid[startIndex][i] == false) {
continue;
}
tmp.add(s.substring(startIndex, i + 1));
dfs(s, i + 1, tmp, res, valid);
tmp.remove(tmp.size() - 1);
}
}
}