Given a string s, partition s such that every substring of the partition is a palindrome.
Return all possible palindrome partitioning of s.
Example:
Input: "aab" Output: [ ["aa","b"], ["a","a","b"] ]
难度:medium
题目:给定一字符串,切分字符串使得每个子串为回文字符串。返回所有可能的切分。
思路:
首先利用动态规划找出所有回文
定义pi 表示从子串p从i到j是回文。
转换方程
p[i][j] = p[i + 1][j - 1] && s[i] == s[j]
然后利用递归收集所有可能的切分
Runtime: 3 ms, faster than 99.87% of Java online submissions for Palindrome Partitioning.
Memory Usage: 39.5 MB, less than 100.00% of Java online submissions for Palindrome Partitioning.
class Solution { public List<List<String>> partition(String s) { if (null == s || s.length() < 1) { return new ArrayList(); } int n = s.length(); if (1 == s.length()) { return Arrays.asList(Arrays.asList(s)); } char[] sc = s.toCharArray(); boolean[][] bc = new boolean[n][n]; // 初始化 p1 p2 for (int i = 0; i < n - 1; i++) { bc[i][i] = true; if (sc[i] == sc[i + 1]) { bc[i][i + 1] = true; } } bc[n - 1][n - 1] = true; // i indicates string length for (int i = 3; i <= n; i++) { // j indicates string index for (int j = 0; j <= n - i; j++) { boolean b = (sc[j] == sc[j + i - 1]); bc[j][j + i - 1] = b && bc[j + 1][j + i - 1 - 1]; } } //收集切分 List<List<String>> result = new ArrayList<>(); buildPalindrome(bc, result, new Stack<>(), s, 0, n); return result; } private void buildPalindrome(boolean[][] bc, List<List<String>> result, Stack<String> stack, String s, int depth, int n) { if (n == depth) { result.add(new ArrayList(stack)); return; } for (int i = depth; i < n; i++) { if (bc[depth][i]) { stack.push(s.substring(depth, i + 1)); buildPalindrome(bc, result, stack, s, i + 1, n); stack.pop(); } } } }