题目
Given a string s, partition s such that every substring of the partition is a palindrome.
Return all possible palindrome partitioning of s.
For example, given s =
"aab"
,
Return[ ["aa","b"], ["a","a","b"] ]
方法一
使用递归的思想:假设字符串的长度为:n,先判断前k个字符构成的字串是不是回文,如果是,则递归求解n-k字串。
//方法一:直接使用递归的思想 //public class LeetCode { // // public boolean isPalindrome(String s) { // int len = s.length(); // for (int i = 0; i < len / 2; i++) { // if (s.charAt(i) != s.charAt(len - 1 - i)) { // return false; // } // } // return true; // } // public List<List<String>> partition(String s) { // // // if (s == null) { // return null; // } else { // int len = s.length(); // List<List<String>> list = new ArrayList<List<String>>(); // if (len == 0) { // List<String> subList = new ArrayList<String>(); // list.add(subList); // }else if (len == 1) { // List<String> subList = new ArrayList<String>(); // subList.add(s); // list.add(subList); // } else { // for (int i = 0; i < len; i++) { // String str = s.substring(0, i + 1); // List<List<String>> subList = null; // if (isPalindrome(str)) { // subList = partition(s.substring(i+1)); // for (List<String> sub: subList) { // sub.add(0,str); // } // for (List<String> sub: subList) { // list.add(sub); // } // } // } // } // // return list; // } // }
方法二
使用DP的思想
先求解 i-j的字串是不是回文串,并将结果放入一个二维数组中去。遍历二维数组,类似于递归。
public class LeetCode { boolean[][] palindromeArray(String s) { int len = s.length(); boolean[][] arrayPal = new boolean[len][len]; for (int interval = 0; interval < len; interval++) { for (int i = 0; i < len - interval; i++) { int j = i + interval; if (i == j){ arrayPal[i][j] = true; } else if (s.charAt(i) == s.charAt(j)) { if (j == i + 1) { arrayPal[i][j] = true; } else if (arrayPal[i + 1][j - 1] == true) { arrayPal[i][j] = true; } else { arrayPal[i][j] = false; } } else { arrayPal[i][j] = false; } } } return arrayPal; } private void getList(String s, boolean[][] status, int start, List<String> array, List<List<String>> result) { if (start == s.length()) { result.add(array); return; } for (int i = start; i < s.length(); i++) { if (status[start][i] == true) { List<String> temp = new ArrayList<String>(array); temp.add(s.substring(start, i + 1)); getList(s, status, i + 1, temp,result); } } } public List<List<String>> partition(String s) { if (s == null) { return null; } else{ List<List<String>> list = new ArrayList<List<String>>(); List<String> subList = new ArrayList<String>(); if (s.length() == 1) { subList.add(s); list.add(subList); return list; } else { boolean[][] status = palindromeArray(s); getList(s, status, 0, subList, list); } return list; } } public static void main(String[] args) { // TODO Auto-generated method stub List<List<String>> list = new LeetCode().partition("aabaa"); for (List<String> sub: list) { System.out.println(sub); } } }