分割回文串
给你一个字符串 s
,请你将 s
分割成一些子串,使每个子串都是
回文串
。返回 s
所有可能的分割方案。
示例 1:
1 2
| 输入:s = "aab" 输出:[["a","a","b"],["aa","b"]]
|
示例 2:
提示:
1 <= s.length <= 16
s
仅由小写英文字母组成
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41
| class Solution { private List<List<String>> res = new ArrayList<>(); private List<String> list = new ArrayList<>(); private String s;
public List<List<String>> partition(String s) { this.s = s; dfs(0); return res; }
private void dfs(int i) { if (i == s.length()) { res.add(new ArrayList<>(list)); return; } for (int j = i; j < s.length(); j++) { if (check(i, j)) { list.add(s.substring(i, j + 1)); dfs(j + 1); list.remove(list.size() - 1); } } }
private boolean check(int i, int j) { while (i < j) { if (s.charAt(i++) != s.charAt(j--)) { return false; } } return true; } }
|