|
| 1 | +package com.diguage.algorithm.leetcode; |
| 2 | + |
| 3 | +import java.util.*; |
| 4 | + |
| 5 | +/** |
| 6 | + * = 131. Palindrome Partitioning |
| 7 | + * |
| 8 | + * https://leetcode.com/problems/palindrome-partitioning/[Palindrome Partitioning - LeetCode] |
| 9 | + * |
| 10 | + * Given a string s, partition s such that every substring of the partition is a palindrome. |
| 11 | + * |
| 12 | + * Return all possible palindrome partitioning of s. |
| 13 | + * |
| 14 | + * .Example: |
| 15 | + * [source] |
| 16 | + * ---- |
| 17 | + * Input: "aab" |
| 18 | + * Output: |
| 19 | + * [ |
| 20 | + * ["aa","b"], |
| 21 | + * ["a","a","b"] |
| 22 | + * ] |
| 23 | + * ---- |
| 24 | + * |
| 25 | + * @author D瓜哥, https://www.diguage.com/ |
| 26 | + * @since 2020-01-04 19:04 |
| 27 | + */ |
| 28 | +public class PalindromePartitioning { |
| 29 | + /** |
| 30 | + * Runtime: 2 ms, faster than 94.23% of Java online submissions for Palindrome Partitioning. |
| 31 | + * Memory Usage: 39.2 MB, less than 95.45% of Java online submissions for Palindrome Partitioning. |
| 32 | + * |
| 33 | + * Copy from: https://leetcode.com/problems/palindrome-partitioning/discuss/41963/Java%3A-Backtracking-solution.[Java: Backtracking solution. - LeetCode Discuss] |
| 34 | + */ |
| 35 | + public List<List<String>> partition(String s) { |
| 36 | + if (Objects.isNull(s) || s.length() == 0) { |
| 37 | + return Collections.emptyList(); |
| 38 | + } |
| 39 | + List<List<String>> result = new LinkedList<>(); |
| 40 | + List<String> current = new ArrayList<>(); |
| 41 | + dfs(s, 0, current, result); |
| 42 | + return result; |
| 43 | + } |
| 44 | + |
| 45 | + private void dfs(String s, int index, List<String> current, List<List<String>> result) { |
| 46 | + if (index == s.length()) { |
| 47 | + result.add(new ArrayList<>(current)); |
| 48 | + } else { |
| 49 | + for (int i = index; i < s.length(); i++) { |
| 50 | + if (isPalindrome(s, index, i)) { |
| 51 | + current.add(s.substring(index, i + 1)); |
| 52 | + dfs(s, i + 1, current, result); |
| 53 | + current.remove(current.size() - 1); |
| 54 | + } |
| 55 | + } |
| 56 | + } |
| 57 | + } |
| 58 | + |
| 59 | + private boolean isPalindrome(String s, int low, int high) { |
| 60 | + while (low < high) { |
| 61 | + if (!Objects.equals(s.charAt(low++), s.charAt(high--))) { |
| 62 | + return false; |
| 63 | + } |
| 64 | + } |
| 65 | + return true; |
| 66 | + } |
| 67 | + |
| 68 | + public static void main(String[] args) { |
| 69 | + PalindromePartitioning solution = new PalindromePartitioning(); |
| 70 | + String s1 = "aab"; |
| 71 | + List<List<String>> r1 = solution.partition(s1); |
| 72 | + System.out.println(Arrays.deepToString(r1.toArray())); |
| 73 | + } |
| 74 | +} |
0 commit comments