题目地址:LeetCode 131.分割回文串
1.问题思路
知题意,将字符串分割成若干个回文串。其实分割问题差不多就是组合问题,依然可以使用回溯思想。面对回溯算法通常使用DFS查找,依据递归三部曲:
- 递归方法参数及返回值
需要得到可能结果一般为void。由于需要对已经分割的子串进行再次分割,直到分割位置到达字符串尾部终止终止,所以还需要startIndex记录分割位置。 - 终止条件
即startIndex=s.length-1时退出 - 本层遍历区间及处理
遍历区间为[startIndex, s.length-1],如当前[i, startIndex]为回文串则需要进行下层遍历dfs(s, startIndex+1),如当前不为回文串则进行剪枝。
2.代码实现
class Solution {
List<List<String>> list = new ArrayList<>();
List<String> path = new ArrayList<>();
public List<List<String>> partition(String s) {
dfs(s, 0);
return list;
}
/**
* 查找分割子串
* 如果当前分割的字符串不是回文串,则返回
* ··· 是回文串, 则从startIndex+1再次切割
* @paam s
* @param startIndex
*/
public void dfs(String s, int startIndex) {
// startIndex超过了s的最大长度,则代表当前分割的字符串全是回文串
if (startIndex >= s.length()) {
list.add(new ArrayList<>(path));
return;
}
// 对当前进行切割
for (int i = startIndex; i < s.length(); i++) {
if (isPalindrome(s, startIndex, i)) {
path.add(s.substring(startIndex, i+1));
} else {
// 剪枝!!! 如果当前为回文串, 则跳过
continue;
}
// 回溯
dfs(s, i + 1);
path.remove(path.size()-1);
}
}
/**
* 双指针思路
* 判断字符串是否是回文字符串
* @param s
* @return
*/
public boolean isPalindrome(String s, int startIndex, int endIndex) {
boolean result = true;
while (startIndex < endIndex) {
if (s.charAt(startIndex) == s.charAt(endIndex)) {
startIndex++;
endIndex--;
} else {
result = false;
break;
}
}
return result;
}
}
483

被折叠的 条评论
为什么被折叠?



