用dw做销售网站,什么是seo营销,怎样做博客网站,哪些网站可以免费推广题目#xff1a;
给你一个字符串 s#xff0c;请你将 s 分割成一些子串#xff0c;使每个子串都是 回文串 。返回 s 所有可能的分割方案。
回文串 是正着读和反着读都一样的字符串。
方法#xff1a;灵神-子集型回溯
假设每对相邻字符之间有个逗号#xff0c;那么就看…题目
给你一个字符串 s请你将 s 分割成一些子串使每个子串都是 回文串 。返回 s 所有可能的分割方案。
回文串 是正着读和反着读都一样的字符串。
方法灵神-子集型回溯
假设每对相邻字符之间有个逗号那么就看每个逗号是选还是不选。
也可以理解成是否要把 s[i]s[i]s[i] 当成分割出的子串的最后一个字符。
代码
class Solution {private final ListListString ans new ArrayList();private final ListString path new ArrayList();private String s;public ListListString partition(String s) {this.s s;dfs(0, 0);return ans;}private boolean isPalindrome(int left, int right) {while (left right) {if (s.charAt(left) ! s.charAt(right--))return false;}return true;}// start 表示当前这段回文子串的开始位置private void dfs(int i, int start) {if (i s.length()) {ans.add(new ArrayList(path));return;}// 不选 i 和 i 1 之间的逗号i n - 1 时一定要选if (i s.length() - 1)dfs(i 1, start);// 选 i 和 i 1 之间的逗号把 s[i] 作为子串的最后一个字符if (isPalindrome(start, i)) {path.add(s.substring(start, i 1));dfs(i 1, i 1); // 下一个子串从 i1 开始path.remove(path.size() - 1); // 恢复现场}}
}