题目描述
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"] ]
求字符串的的所有划分字符串列表,使得划分后的每一个字符串是回文字符串。
解题思路
采用递归的思路:
- 划分字符串,将数组划分为[0,i]和[i,n-1]的子字符串(其中0<i<n);
- 判断[0,i]是否是回文数,如果是的话求partition([i,n-1]),并将[0,i]添加到返回的列表中;
- 循环1、2,直到i==n - 1;
代码
/**
* 划分字符串,将数组划分为[0,i]和[i,n-1]的子字符串(其中0<i<n)
* 判断[0,i]是否是回文数,如果是的话求partition([i,n-1]),并将[0,i]添加到返回的列表中
* @param s
* @return
*/
public static List<List<String>> partition(String s) {
int n = s.length();
List<List<String>> result = new ArrayList<List<String>>();
//len为每次字符串划分的位置
for (int len = 1; len <= n; len++) {
//划分字符串
String subStr1 = s.substring(0, len);
String subStr2 = s.substring(len, n);
if (isPalindrome(subStr1)) {
if (subStr2.equals("")) {
List<String> list = new ArrayList<String>();
list.add(subStr1);
result.add(list);
} else {
List<List<String>> subList = partition(subStr2);
if (subList.size() > 0) {
for (List<String> l : subList) {
l.add(0,subStr1);
}
result.addAll(subList);
}
}
}
}
return result;
}
/**
* 判断一个字符串是否是回文字符串
* @param s
* @return
*/
public static boolean isPalindrome(String s) {
int start = 0;
int end = s.length() - 1;
while (start < end) {
if (s.charAt(start) == s.charAt(end)) {
start++;
end--;
} else {
return false;
}
}
return true;
}