[刷题]Palindrome Partitioning
public class Solution {
/**
* @param s: A string
* @return: A list of lists of string
*/
public List<List<String>> partition(String s) {
// 2015-07-08
List<List<String>> rst = new ArrayList<List<String>>();
if (s == null || s.length() == 0) {
return rst;
}
ArrayList<String> list = new ArrayList<>();
helper(rst, list, s, 0);
return rst;
}
// 注意第一个参数的类型
private void helper(List<List<String>> rst, ArrayList<String> list, String s, int pos) {
if (pos == s.length()) {
rst.add(new ArrayList<String>(list));
return;
}
for (int i = pos + 1; i <= s.length(); i++) { //注意是<=
if (!isPalindrome(s.substring(pos, i))) {
continue;
}
list.add(s.substring(pos, i));
helper(rst, list, s, i);
list.remove(list.size() - 1);
}
return;
}
private boolean isPalindrome(String s) {
if (s.length() == 0) {
return true;
}
int start = 0;
int end = s.length() - 1;
while (start < end) {
if (s.charAt(start) != s.charAt(end)) {
return false;
}
start++;
end--;
}
return true;
}
}