Skip to content

Instantly share code, notes, and snippets.

@cxtadment
Created September 3, 2015 18:00
Show Gist options
  • Select an option

  • Save cxtadment/074c44d88e854d6e5de3 to your computer and use it in GitHub Desktop.

Select an option

Save cxtadment/074c44d88e854d6e5de3 to your computer and use it in GitHub Desktop.
public class Solution {
/**
* @param s: A string
* @return: A list of lists of string
*/
public List<List<String>> partition(String s) {
// write your code here
List<List<String>> result = new ArrayList<>();
if (s == null || s.isEmpty()) {
return result;
}
List<String> palindrome = new ArrayList<>();
partitionHelper(s, 0, result, palindrome);
return result;
}
public void partitionHelper(String s, int pos, List<List<String>> result, List<String> palindrome){
if (s.length() == pos) {
result.add(new ArrayList<String>(palindrome));
return;
}
for (int i = pos + 1; i <= s.length(); i++) {
String temp = s.substring(pos, i);
if (!isPalindrome(temp)) {
continue;
}
palindrome.add(temp);
partitionHelper(s, i, result, palindrome);
palindrome.remove(palindrome.size() - 1);
}
}
public boolean isPalindrome(String words) {
if (words == null || words.isEmpty()) {
return false;
}
int length = words.length();
for (int i = 0; i < length - i; i++) {
if (words.charAt(i) != words.charAt(length - i - 1)) {
return false;
}
}
return true;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment