131. 分割回文串

描述

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

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

链接

131. 分割回文串 - 力扣(LeetCode) (leetcode-cn.com)

 

解法

 1 class Solution {
 2     List<List<String>> res = new ArrayList<>();
 3     Deque<String> path = new LinkedList<>();
 4     public List<List<String>> partition(String s) {
 5         if (s.length() == 0) return res;
 6         BackTracking(s, 0);
 7         return res;
 8     }
 9 
10     public void BackTracking(String s, int index) {
11         if(index >= s.length()) {
12             res.add(new ArrayList<>(path));
13             return;
14         }
15         for (int i = index; i < s.length(); i++) {
16             if (isPaLinDrome(s, index, i)) {
17                 String str = s.substring(index, i+1);
18                 path.add(str);
19             } else {
20                 continue;
21             }
22             BackTracking(s, i + 1);
23             path.removeLast();
24         }
25     }
26 
27     public Boolean isPaLinDrome(String s, int left, int right) {
28         for( int i = left, j = right; i < j; i++, j--) {
29             if(s.charAt(i) != s.charAt(j)) {
30                 return false;
31             }
32         }
33         return true;
34     }
35 }

 

参考

carl

posted @ 2021-12-20 20:05  DidUStudy  阅读(27)  评论(0编辑  收藏  举报