|
| 1 | +package org.gd.leetcode.p0132; |
| 2 | + |
| 3 | +import org.gd.leetcode.common.LeetCode; |
| 4 | + |
| 5 | +/** |
| 6 | + * TODO: https://leetcode.com/problems/palindrome-partitioning-ii/ |
| 7 | + * |
| 8 | + * @author Horkhover D. |
| 9 | + * @see org.gd.leetcode.p0131.Solution |
| 10 | + * @since 2020-07-13.07.2020 |
| 11 | + */ |
| 12 | +@SuppressWarnings("JavadocReference") |
| 13 | +@LeetCode( |
| 14 | + name = "Palindrome Partitioning II", |
| 15 | + difficulty = LeetCode.Level.HARD, |
| 16 | + state = LeetCode.State.TIME_LIMIT_EXCEEDED, |
| 17 | + tags = { |
| 18 | + LeetCode.Tags.DYNAMIC_PROGRAMMING |
| 19 | + } |
| 20 | +) |
| 21 | +class Solution { |
| 22 | + |
| 23 | + private int min; |
| 24 | + |
| 25 | + @SuppressWarnings("DuplicatedCode") |
| 26 | + private static boolean isPalindrome(String word) { |
| 27 | + final int length = word.length(); |
| 28 | + if (length == 0) |
| 29 | + return false; |
| 30 | + if (length == 1) |
| 31 | + return true; |
| 32 | + int mid = length >> 1; |
| 33 | + for (int i = 0; i <= mid; i++) { |
| 34 | + int j = length - 1 - i; |
| 35 | + if (word.charAt(i) != word.charAt(j)) |
| 36 | + return false; |
| 37 | + } |
| 38 | + return true; |
| 39 | + } |
| 40 | + |
| 41 | + private void partition(final int cuts, |
| 42 | + final String word) { |
| 43 | + |
| 44 | + final int wordLength = word.length(); |
| 45 | + if (wordLength == 0) { |
| 46 | + min = Math.min(min, cuts - 1); |
| 47 | + return; |
| 48 | + } |
| 49 | + if (wordLength == 1) { |
| 50 | + min = Math.min(min, cuts); |
| 51 | + return; |
| 52 | + } |
| 53 | + |
| 54 | + for (int i = 1; i <= wordLength; i++) { |
| 55 | + String ss = word.substring(0, i); |
| 56 | + if (isPalindrome(ss)) { |
| 57 | + partition(cuts + 1, word.substring(i, wordLength)); |
| 58 | + } |
| 59 | + } |
| 60 | + } |
| 61 | + |
| 62 | + public int minCut(String word) { |
| 63 | + min = Integer.MAX_VALUE; |
| 64 | + partition(0, word); |
| 65 | + return min; |
| 66 | + } |
| 67 | +} |
0 commit comments