问题:
给定一个字符串 s,请将 s 分割成一些子串,使每个子串都是 回文串 。返回 s 所有可能的分割方案。
回文串 是正着读和反着读都一样的字符串。
示例 1:
输入:s = "aab"
输出:[["a","a","b"],["aa","b"]]
示例 2:
输入:s = "a"
输出:[["a"]]
提示:
1 <= s.length <= 16
s 仅由小写英文字母组成
解答思路:
一、题目分析:本题要求将给定的字符串分割成回文子串,并返回所有可能的分割方案。
二、主要思路:
1. 定义一个辅助函数'isPalindrome'来判断一个字符串是否为回文串。
2. 使用深度优先搜索(DFS)来遍历字符串的所有可能分割点。
3. 在 DFS 过程中,从字符串的开头开始,尝试将其分割为一个回文子串和剩余部分。
4. 如果剩余部分为空,则将当前分割方案添加到结果列表中。
5. 否则,继续对剩余部分进行 DFS 分割。
6. 最终返回结果列表。
三、以下是修改后的 Java 代码:
import java.util.ArrayList;
import java.util.List;
public class PalindromePartitioning {
public List<List<String>> partition(String s) {
List<List<String>> result = new ArrayList<>();
dfs(s, 0, new ArrayList<>(), result);
return result;
}
private void dfs(String s, int start, List<String> current, List<List<String>> result) {
if (start == s.length()) {
result.add(new ArrayList<>(current));
return;
}
for (int i = start; i < s.length(); i++) {
if (isPalindrome(s, start, i)) {
current.add(s.substring(start, i + 1));
dfs(s, i + 1, current, result);
current.remove(current.size() - 1);
}
}
}
private boolean isPalindrome(String s, int start, int end) {
while (start < end) {
if (s.charAt(start++)!= s.charAt(end--)) {
return false;
}
}
return true;
}
public static void main(String[] args) {
String s = "aab";
PalindromePartitioning solution = new PalindromePartitioning();
List<List<String>> result = solution.partition(s);
for (List<String> partition : result) {
System.out.println(partition);
}
}
}
(文章为作者在学习java过程中的一些个人体会总结和借鉴,如有不当、错误的地方,请各位大佬批评指正,定当努力改正,如有侵权请联系作者删帖。)