131. Palindrome Partitioning
Description
Given a string s, partition s such that every substring of the partition is a palindrome.
Return all possible palindrome partitioning of s.
Constraints
Approach
Links
GeeksforGeeks
YouTube
Examples
Input: "aab"
Output:
[
["aa", "b"],
["a", "a", "b"]
]
Solutions
/**
* Time complexity :
* Space complexity :
*/
class Solution {
public List<List<String>> partition(String s) {
List<List<String>> resultList = new ArrayList();
if(s == null || s.length() == 0) return resultList;
helper(resultList, new ArrayList(), s, 0);
return resultList;
}
private void helper(List<List<String>> resultList,
List<String> currList,
String s,
int start) {
if(start == s.length()) {
resultList.add(new ArrayList(currList));
return;
}
for(int i = start; i < s.length(); i++) {
if(isPalindrome(s, start, i)) {
currList.add(s.substring(start, i+1));
helper(resultList, currList, s, i+1);
currList.remove(currList.size()-1);
}
}
}
private boolean isPalindrome(String s, int left, int right) {
while(left < right) {
if(s.charAt(left) != s.charAt(right)) {
return false;
}
left++;
right--;
}
return true;
}
}
Follow up
Last updated
Was this helpful?