131. 分割回文串
题目来源
题目分析
这道题目要求我们将字符串 s
分割成一些子串,使得每个子串都是回文串。最终,返回所有可能的分割方案。这意味着我们需要遍历所有可能的分割点,并检查每个子串是否为回文。
给你一个字符串 s,请你将 s 分割成一些子串,使每个子串都是回文串 。返回 s 所有可能的分割方案。
题目难度
- 难度:中等
题目标签
- 标签:回溯
题目限制
1 <= s.length <= 16
s
仅由小写英文字母组成
解题思路
为了解决这个问题,我们可以使用回溯算法。在回溯过程中,我们需要枚举所有可能的分割点,并判断每个子串是否为回文串。如果是回文,则继续递归分割下一个子串;否则跳过当前分割点。
核心算法步骤
-
输入角度的回溯:
- 我们从第一个字符开始枚举所有可能的分割点
i
。 - 对于每个
i
,检查从start
到i
的子串是否为回文。 - 如果是回文串,则继续从下一个字符开始递归处理剩余的字符串。
- 我们从第一个字符开始枚举所有可能的分割点
-
答案角度的回溯:
- 在每次递归时,将当前路径上的子串添加到结果集中。
- 枚举每个可能的分割点,检查子串是否为回文串,然后继续递归分割。
-
回文判断:
- 使用相向双指针判断,设置
left
和right
指针,分别指向字符串s
的首尾 - 如果
left
和right
指向的字符相同,则left
和right
更新,left
向后,right
向前,最后遍历完s
返回true
。 - 如果
left
和right
指向的字符不同直接返回false
- 使用相向双指针判断,设置
代码实现
以下是实现字符串回文分割的Java代码:
/**
* 131. 分割回文串
* @param s 输入的字符串
* @return ans 所有可能的分割方案
*/
public List<List<String>> partition(String s) {
List<List<String>> ans = new ArrayList<>();
if (s.isEmpty()) {
return ans;
}
partition(s, 0, 0, new ArrayList<>(), ans);
return ans;
}
// 输入角度的回溯
private void partition(String s, int i, int start, ArrayList<String> path, List<List<String>> ans) {
if (i == s.length()) {
ans.add(new ArrayList<>(path));
return;
}
if (i < s.length() - 1) {
partition(s, i + 1, start, path, ans);
}
if (isPalindrome(s.substring(start, i + 1))) {
path.add(s.substring(start, i + 1));
partition(s, i + 1, i + 1, path, ans);
path.remove(path.size() - 1);
}
}
// 判断s是否为回文串
public boolean isPalindrome(String s) {
int left = 0;
int right = s.length() - 1;
while (left < right) {
if (s.charAt(left) != s.charAt(right)) {
return false;
}
left++;
right--;
}
return true;
}
// 答案角度的回溯,枚举子串的结束点也就是下一个分割点的位置
private void partition2(String s, int i, ArrayList<String> path, List<List<String>> ans) {
if (i == s.length()) {
ans.add(new ArrayList<>(path));
return;
}
for (int j = i; j < s.length(); j++) {
if (isPalindrome(s.substring(i, j + 1))) {
path.add(s.substring(i, j + 1));
partition2(s, j + 1, path, ans);
path.remove(path.size() - 1);
}
}
}
代码解读
-
输入角度的回溯:
- 从索引
i
开始递归,如果当前子串是回文,则将其加入路径,并继续递归处理剩余字符串。 - 通过检查每个分割点,确保只将回文串加入路径。
- 从索引
-
答案角度的回溯:
- 每次递归时,将当前路径添加到结果集中。
- 通过枚举可能的分割点,逐步构建回文子串,并将每个满足条件的子串加入路径。
性能分析
-
时间复杂度:
O(N * 2^N)
,其中N
是字符串的长度。每个字符可能作为回文串的开始和结束点,最多有2^N
种分割方案。 -
空间复杂度:
O(N)
,递归调用栈的深度为N
。
测试用例
你可以使用以下测试用例来验证代码的正确性:
String s = "aab";
List<List<String>> result = partition(s);
System.out.println(result);
// 输出: [["a","a","b"],["aa","b"]]
总结
这道题目通过回溯算法帮助我们理解了如何通过枚举分割点来构建所有可能的回文子串。无论从输入角度还是答案角度,我们都可以高效地解决问题,并找到所有可能的分割方案。