Given a string s, partition s such that every substring of the partition is a palindrome.
Return all possible palindrome partitioning of s.
For example, given s = "aab",
Return
[
["aa","b"],
["a","a","b"]
]
这种要返回所有结果的题目看起来是要用递归的,DFS暴力搜索就好了。
public class Solution {
public List<List<String>> partition(String s) {
List<List<String>> res = new ArrayList<List<String>>();
if(s == null || s.length() == 0)
return res;
dfs(s, 0, new ArrayList<String>(), res);
return res;
}
public void dfs(String s, int start, List<String> strs, List<List<String>> res){
if(start >= s.length()){
res.add(new ArrayList<String>(strs));
return;
}
for(int i = start; i < s.length(); i++){
if(isPalindrome(s, start, i)){
strs.add(s.substring(start, i + 1));
dfs(s, i + 1, strs, res);
strs.remove(strs.size() - 1);
}
}
}
public boolean isPalindrome(String s, int start, int end){
int i = start, j = end;
while(i < j){
if(s.charAt(i) != s.charAt(j))
return false;
i++;
j--;
}
return true;
}
}

本文介绍了一种使用递归深度优先搜索(DFS)算法解决字符串回文分组的问题。通过实例演示了如何找到所有可能的回文子串组合,包括示例解析和代码实现。
5514

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



