Question
Given a string s, partition s such that every substring of the partition is a palindrome.
Return all possible palindrome partitioning of s.
给出一个字符串s,将s分割为回文字串,返回所有的分割方法
Example
given s = “aab”,
Return:
[
[“aa”,”b”],
[“a”,”a”,”b”]
]
Solution
回溯解。每次对以当前字符开头的字符串进行判断是否是回文字符串,如果是则判断之后的字符串,否则跳过。比如”aab”,首先判断以a开头的字符串是否是回文字符串,”a”,”aa”,”aab”,而其中”a”和”aa”是回文字符串,所以分别按同样的方法继续哦判断”ab”,”b”。
public class Solution { public List<List<String>> partition(String s) { List<List<String>> res = new ArrayList<>(); backtracking(s, 0, res, new ArrayList<>()); return res; } /** * 思路:每次对以当前开始索引开头的字符串进行判断是否是回文字符串, * 如果是则判断接下去的字符串,否则跳过。 * @param s:需要分割的字符串 * @param start:字符串开头索引 * @param res:保存分割结果 * @param temp:保存当前组合结果 */ public void backtracking(String s, int start, List<List<String>> res, List<String> temp){ // 如果已经分割完字符串则添加到结果集 // 因为单个字符串也算回文字符串,所以不会出现分割完却有某个字符串不是回文的情况 if(start == s.length()){ res.add(new ArrayList<>(temp)); } // 判断以s[i]字符开头的字符串是否有回文字符串 for(int i = start; i < s.length();i++){ // 如果是回文则继续判断该回文字符串后面的字符串 if(isPalindrome(s, start, i)){ temp.add(s.substring(start, i + 1)); backtracking(s, i + 1, res, temp); temp.remove(temp.size() - 1); } } } /** * 思路:判断字符串s[l:r]是否为回文字符串 * @param s:字符串 * @param l:字符串开头索引 * @param r:字符串结尾索引 * @return:是否为字符串,是则True,否则False */ public boolean isPalindrome(String s, int l, int r){ if(l > r) return true; if(s.charAt(l) != s.charAt(r)) return false; return isPalindrome(s, l + 1, r - 1); } }