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"] ]感觉这道题和Restore IP Address那道题差不多,这两道题适合多做几遍。尤其注意substring的截法。
注意回文数的判断方法。
Source
public class Solution {
public List<List<String>> partition(String s) {
List<List<String>> st = new ArrayList<List<String>>();
List<String> a = new ArrayList<String>();
if(s.length() == 0){
return st;
}
dfs(0, s, st, a);
return st;
}
public boolean isPalindrome(String s){
int low = 0, high = s.length() - 1;
while(low < high){
if(s.charAt(low) != s.charAt(high))
return false;
low++;
high--;
}
return true;
}
public void dfs(int start, String s, List<List<String>> st, List<String> a){
if(start == s.length()){ //实在找不到结束条件的时候就设个start
st.add(new ArrayList<String>(a));
return ;
}
for(int i = start; i < s.length(); i++){
String temp = s.substring(start, i + 1); //注意起始位置是start
if(isPalindrome(temp)){
a.add(temp);
dfs(i + 1, s, st, a);
a.remove(a.size() - 1);
}
}
}
}
Test
public static void main(String[] args){
String s = "aab";
System.out.println(new Solution().partition(s));
}