shriyanshi24jindal

Print all palindromes in Palindrome Partitioning

Mar 30th, 2026
116
0
Never
Not a member of GistPad yet? Sign Up, it unlocks many cool features!
Java 8.77 KB | None | 0 0
  1. class Solution {
  2. /**
  3.   []
  4.   / \
  5.   "a" "aa"
  6.   / \
  7.   "a" "b"
  8.   | |
  9.   "b" END
  10.   |
  11.   END
  12.   */
  13.  
  14. public List<List<String>> partition(String s) {
  15. List<List<String>> result = new ArrayList<>();
  16. List<String> current = new ArrayList<>();
  17.  
  18. solve(s, 0, s.length(), result, current);
  19. return result;
  20. }
  21.  
  22. public void solve(String s, int i, int j, List<List<String>> result, List<String> current)
  23. {
  24. // base condition
  25. if(i == s.length()) {
  26. result.add(new ArrayList<>(current));
  27. return;
  28. }
  29. // Define k-loop scheme
  30. for(int k=i; k<=j-1; k++)
  31. {
  32. if(isPalindrome(s, i, k))
  33. {
  34. // choose
  35. current.add(s.substring(i, k+1));
  36.  
  37. // explore
  38. solve(s, k+1, j, result, current);
  39.  
  40. // un-choose (backtrack)
  41. current.remove(current.size() - 1);
  42. }
  43. }
  44. return;
  45. }
  46.  
  47. public boolean isPalindrome(String s, int i, int j)
  48. {
  49. String s1 = s.substring(i, j+1);
  50. String s2 = new StringBuilder(s1).reverse().toString();
  51.  
  52. return s1.equals(s2);
  53. }
  54. }
RAW Paste Data Copied