2022-4-3 高频题

给你一个字符串 s,请你将 s 分割成一些子串,使每个子串都是 回文串 。返回 s 所有可能的分割方案。

回文串 是正着读和反着读都一样的字符串。

 

 1 class Solution {
 2     public List<List<String>> partition(String s) {
 3         List<List<String>> ans=new ArrayList<>();
 4         if (s.length()==0) return ans;
 5         if (s.length()==1){
 6             ans.add(new ArrayList<>(List.of(s)));
 7             return ans;
 8         }
 9         int n=s.length();
10         for (int i=0;i<n;i++) {
11             //0~i长度
12             if (check(s.substring(0,i+1))) {
13                 List<List<String>> temp=partition(s.substring(i+1));
14                 if (temp.size()==0) {
15                     ans.add(List.of(s));
16                     continue;
17                 }
18                 for (int j=0;j<temp.size();j++) {
19                     List<String> list=temp.get(j);
20                     List<String> alist=new ArrayList<>();
21                     alist.add(s.substring(0,i+1));
22                     alist.addAll(list);
23                     ans.add(alist);
24                 }
25             }
26         }
27         return ans;
28     }
29 
30     public boolean check(String s){
31         int l=0,r=s.length()-1;
32         while (l<r) {
33             if (s.charAt(l)!=s.charAt(r)) return false;
34             l++;
35             r--;
36         }
37         return true;
38     }
39 }

递归实现。

更快的dfs+动态规划预处理。

posted on 2022-04-03 14:00  阿ming  阅读(25)  评论(0)    收藏  举报

导航