Skip to content

Instantly share code, notes, and snippets.

@cangoal
Created June 4, 2015 19:14
Show Gist options
  • Save cangoal/d5c666968bf07f85d2e7 to your computer and use it in GitHub Desktop.
Save cangoal/d5c666968bf07f85d2e7 to your computer and use it in GitHub Desktop.
LeetCode - Palindrome Partitioning
public ArrayList<ArrayList<String>> partition(String s) {
ArrayList<ArrayList<String>> ret = new ArrayList<ArrayList<String>>();
if(s == null || s.length()==0) return ret;
helper(ret, s, new ArrayList<String>());
return ret;
}
public void helper(ArrayList<ArrayList<String>> ret, String s, ArrayList<String> lst){
if(s.length() == 0){
ret.add(new ArrayList<String>(lst));
return;
}
for(int i=1; i <= s.length(); i++){ // don't forget to consider "=" case
String cur = s.substring(0, i);
if(IsPalindrome(cur)){
lst.add(cur);
helper(ret, s.substring(i), lst);
lst.remove(lst.size()-1);
}
}
}
public boolean IsPalindrome(String str){
if(str == null || str.length() == 0) return false;
int left = 0, right = str.length() - 1;
while(left < right){
if(str.charAt(left) != str.charAt(right)){
return false;
}
left++;
right--;
}
return true;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment