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"]
]
题目的意思:给出一串字符,输出将字符串拆分使每个子字符串均为回文串的集合。
也是很简单的回溯就可以了,区别前面的多了一个回文串判断函数
class Solution {
public List<List<String>> partition(String s) {
List<List<String>> result=new ArrayList<>();
List<String> temp=new ArrayList<>();
if(s.length() == 0) return null;
backTrack(result,temp,s);
return result;
}
private void backTrack(List<List<String>> result,List<String> temp,String s){
if(s.length() == 0){
result.add(new ArrayList<>(temp));
}
for(int i=0;i<s.length();i++){
if(isPalindrome(s,0,i)){//判断前i位是否为回文串
temp.add(s.substring(0,i+1));//是就获取s的前i位
backTrack(result,temp,s.substring(i+1));//s.substring(i)表示获取s的第i位之后的字符(包含第i位)
temp.remove(temp.size()-1);
}
}
}
private boolean isPalindrome(String s,int left,int right){
while(left < right){
if(s.charAt(left) != s.charAt(right)) return false;
left++;
right--;
}
return true;
}
}