131. Palindrome Partitioning
Given a strings, partitionssuch that every substring of the partition is a palindrome.
Return all possible palindrome partitioning ofs.
For example, givens="aab",Return
[
["aa","b"],
["a","a","b"]
]
思路:用经典traceback
public class Solution {
public List<List<String>> partition(String s) {
List<List<String>> res = new ArrayList<List<String>>();
if (s==null||s.length()==0) return res;
List<String> temp = new ArrayList<String>();
traceBack(res, temp, s, 0);
return res;
}
public void traceBack(List<List<String>> res, List<String> temp, String s, int startInd){
if (startInd == s.length()){
res.add(new ArrayList<String>(temp));
return;
}
for (int i=startInd;i<s.length();i++){
String subString = s.substring(startInd,i+1);
if (isPalindrome(subString)){
temp.add(subString);
traceBack(res,temp,s,i+1);
temp.remove(temp.size()-1);
}
}
}
public boolean isPalindrome(String s){
int left = 0;
int right = s.length()-1;
while(left<right){
if(s.charAt(left)!=s.charAt(right)){
return false;
}
left++;
right--;
}
return true;
}
}