Advertisement
Guest User

Untitled

a guest
Sep 3rd, 2015
69
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.37 KB | None | 0 0
  1. public class Solution {
  2. /**
  3. * @param s: A string
  4. * @return: A list of lists of string
  5. */
  6. public List<List<String>> partition(String s) {
  7. // write your code here
  8. List<List<String>> result = new ArrayList<>();
  9. if (s == null || s.isEmpty()) {
  10. return result;
  11. }
  12. List<String> palindrome = new ArrayList<>();
  13. partitionHelper(s, 0, result, palindrome);
  14. return result;
  15. }
  16.  
  17. public void partitionHelper(String s, int pos, List<List<String>> result, List<String> palindrome){
  18. if (s.length() == pos) {
  19. result.add(new ArrayList<String>(palindrome));
  20. return;
  21. }
  22.  
  23. for (int i = pos + 1; i <= s.length(); i++) {
  24. String temp = s.substring(pos, i);
  25. if (!isPalindrome(temp)) {
  26. continue;
  27. }
  28. palindrome.add(temp);
  29. partitionHelper(s, i, result, palindrome);
  30. palindrome.remove(palindrome.size() - 1);
  31. }
  32. }
  33.  
  34. public boolean isPalindrome(String words) {
  35. if (words == null || words.isEmpty()) {
  36. return false;
  37. }
  38. int length = words.length();
  39. for (int i = 0; i < length - i; i++) {
  40. if (words.charAt(i) != words.charAt(length - i - 1)) {
  41. return false;
  42. }
  43. }
  44. return true;
  45. }
  46. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement