0% found this document useful (0 votes)
3 views

7. Palindrome Partitioning

Uploaded by

himalayas
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views

7. Palindrome Partitioning

Uploaded by

himalayas
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 1

7.

Palindrome Partitioning
Medium
Given a string s , partition s such that every substring of the partition is a palindrome.
Return all possible palindrome partitioning of s .

class Solution {
List<List<String>> res = new ArrayList<>();

public List<List<String>> partition(String s) {


findPartition(s, 0, new ArrayList<>());
return res;
}

public void findPartition(String s, int idx, List<String> sub) {


if (idx == s.length()) {
res.add(new ArrayList<>(sub));
return;
}
for (int i = idx; i < s.length(); i++) {
if (isPalindrome(s, idx, i)) {
sub.add(s.substring(idx, i + 1));
findPartition(s, i + 1, sub);
sub.remove(sub.size() - 1);
}
}
}

private boolean isPalindrome(String s, int left, int right) {


while (right > left) {
if (s.charAt(left) != s.charAt(right)) {
return false;
}
left++;
right--;
}
return true;
}
}
Time Complexity : O(n^2 * 2^n) | Space Complexity : O(n * 2^n)
Runtime 8ms | Beats 57.12%

You might also like