|
| 1 | +package pp.arithmetic.leetcode; |
| 2 | + |
| 3 | +import pp.arithmetic.Util; |
| 4 | + |
| 5 | +import java.util.ArrayList; |
| 6 | +import java.util.List; |
| 7 | + |
| 8 | +/** |
| 9 | + * Created by wangpeng on 2019-12-24. |
| 10 | + * 131. 分割回文串 |
| 11 | + * |
| 12 | + * 给定一个字符串 s,将 s 分割成一些子串,使每个子串都是回文串。 |
| 13 | + * |
| 14 | + * 返回 s 所有可能的分割方案。 |
| 15 | + * |
| 16 | + * 示例: |
| 17 | + * |
| 18 | + * 输入: "aab" |
| 19 | + * 输出: |
| 20 | + * [ |
| 21 | + * ["aa","b"], |
| 22 | + * ["a","a","b"] |
| 23 | + * ] |
| 24 | + * |
| 25 | + * 来源:力扣(LeetCode) |
| 26 | + * 链接:https://leetcode-cn.com/problems/palindrome-partitioning |
| 27 | + * 著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。 |
| 28 | + */ |
| 29 | +public class _131_partition { |
| 30 | + |
| 31 | + public static void main(String[] args) { |
| 32 | + _131_partition partition = new _131_partition(); |
| 33 | + Util.printLists(partition.partition("aab")); |
| 34 | + Util.printLists(partition.partition("abbaa")); |
| 35 | + Util.printLists(partition.partition("")); |
| 36 | + } |
| 37 | + |
| 38 | + /** |
| 39 | + * 解题思路:DFS遍历+回溯 |
| 40 | + * 1、DFS遍历,从s的第一位开始,逐步判断至最后一位 |
| 41 | + * 2、定义一个skip=1,从1开始,代表从当前位加上skip的结果是否是回文 |
| 42 | + * 3、定义一个循环,位置从0开始,得到所有的结果 |
| 43 | + * |
| 44 | + * 执行用时 :8 ms, 在所有 java 提交中击败了20.05%的用户 |
| 45 | + * 内存消耗 :38.1 MB, 在所有 java 提交中击败了97.34%的用户 |
| 46 | + * |
| 47 | + * @param s |
| 48 | + * @return |
| 49 | + */ |
| 50 | + public List<List<String>> partition(String s) { |
| 51 | + List<List<String>> retList = new ArrayList<>(); |
| 52 | + dfs(retList,new ArrayList<>(),s,0); |
| 53 | + return retList; |
| 54 | + } |
| 55 | + |
| 56 | + private void dfs(List<List<String>> retList, List<String> itemList, String s, int index) { |
| 57 | + if (index > s.length()-1){ |
| 58 | + retList.add(new ArrayList<>(itemList)); |
| 59 | + return; |
| 60 | + } |
| 61 | + int skip = 1; |
| 62 | + while (skip + index <= s.length()) { |
| 63 | + String sub = s.substring(index, index + skip); |
| 64 | + if (isPlalindrome(sub)) { |
| 65 | + itemList.add(sub); |
| 66 | + dfs(retList, itemList, s, index + skip); |
| 67 | + if (itemList.size() > 0) { |
| 68 | + itemList.remove(itemList.size() - 1); |
| 69 | + } |
| 70 | + } |
| 71 | + skip++; |
| 72 | + } |
| 73 | + } |
| 74 | + |
| 75 | + //是否是回文 |
| 76 | + private boolean isPlalindrome(String s) { |
| 77 | + int si = 0, ei = s.length() - 1; |
| 78 | + while (si < ei) { |
| 79 | + if (s.charAt(si) != s.charAt(ei)) return false; |
| 80 | + si++; |
| 81 | + ei--; |
| 82 | + } |
| 83 | + return true; |
| 84 | + } |
| 85 | +} |
0 commit comments