1. 程式人生 > 其它 >2022-4-3 高頻題

2022-4-3 高頻題

131. 分割回文串

給你一個字串 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+動態規劃預處理。