|
| 1 | +package medium; |
| 2 | + |
| 3 | +import java.util.ArrayList; |
| 4 | +import java.util.List; |
| 5 | + |
| 6 | +public class PalindromePartitioning { |
| 7 | + |
| 8 | + |
| 9 | + public List<List<String>> partition(String s) { |
| 10 | + List<List<String>> result = new ArrayList(); |
| 11 | + int n = s.length(); |
| 12 | + boolean[][] dp = new boolean[n][n]; |
| 13 | + for(int i = 0; i < n; i++){ |
| 14 | + for(int j = 0; j <= i; j++){ |
| 15 | + if(s.charAt(j) == s.charAt(i) && (j+1 >= i-1 || dp[j+1][i-1])){// j+1 >= i-1 means j and i are adjance to each other or only one char apart from each other |
| 16 | + //dp[j+1][i-1] means its inner substring is a palindrome, so as long as s.charAt(j) == s.charAt(i), then dp[j][i] must be a palindrome. |
| 17 | + dp[j][i] = true; |
| 18 | + } |
| 19 | + } |
| 20 | + } |
| 21 | + |
| 22 | + for(boolean[] list : dp){ |
| 23 | + for(boolean b : list){ |
| 24 | + System.out.print(b + ", "); |
| 25 | + } |
| 26 | + System.out.println(); |
| 27 | + } |
| 28 | + System.out.println(); |
| 29 | + |
| 30 | + backtracking(s, 0, dp, new ArrayList(), result); |
| 31 | + |
| 32 | + return result; |
| 33 | + } |
| 34 | + |
| 35 | + void backtracking(String s, int start, boolean[][] dp, List<String> temp, |
| 36 | + List<List<String>> result) { |
| 37 | + if (start == s.length()) { |
| 38 | + List<String> newTemp = new ArrayList(temp); |
| 39 | + result.add(newTemp); |
| 40 | + } |
| 41 | + for (int i = start; i < s.length(); i++) { |
| 42 | + if (dp[start][i]) { |
| 43 | + temp.add(s.substring(start, i + 1)); |
| 44 | + backtracking(s, i + 1, dp, temp, result); |
| 45 | + temp.remove(temp.size() - 1); |
| 46 | + } |
| 47 | + } |
| 48 | + } |
| 49 | + |
| 50 | + |
| 51 | + public static void main(String...strings){ |
| 52 | + PalindromePartitioning test = new PalindromePartitioning(); |
| 53 | + String s = "aab"; |
| 54 | + List<List<String>> result = test.partition(s); |
| 55 | + for(List<String> list : result){ |
| 56 | + for(String str : list){ |
| 57 | + System.out.print(str + ", "); |
| 58 | + } |
| 59 | + System.out.println(); |
| 60 | + } |
| 61 | + } |
| 62 | + |
| 63 | +} |
0 commit comments