Skip to content

Commit 50e6081

Browse files
authored
Create PalindromePartitioning.java
1 parent ba2c250 commit 50e6081

File tree

1 file changed

+38
-0
lines changed

1 file changed

+38
-0
lines changed
+38
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,38 @@
1+
//LeetCode 131. Palindrome Partitioning
2+
//Question - https://leetcode.com/problems/palindrome-partitioning/
3+
4+
class Solution {
5+
public List<List<String>> partition(String s) {
6+
List<List<String>> res = new ArrayList<>();
7+
helper(s, 0, new ArrayList<String>(), res);
8+
return res;
9+
}
10+
11+
public void helper(String s, int index, List<String> l, List<List<String>> res){
12+
//Base condition
13+
if(index == s.length()){
14+
res.add(new ArrayList<>(l));
15+
return;
16+
}
17+
18+
//starting from each index, evaluate substrings of all lengths. Check if each
19+
//substring is a palindrome or not. If it is a palindrome, go deeper into
20+
//recursion to see if it is possible to break down the remaining string into
21+
//palindromic substrings or not.
22+
for(int i = index ; i < s.length() ; i++){
23+
if(isPalin(s, index, i)){
24+
l.add(s.substring(index, i+1));
25+
helper(s, i+1, l, res);
26+
l.remove(l.size()-1);
27+
}
28+
}
29+
}
30+
31+
public boolean isPalin(String s, int start, int end){
32+
while(start < end){
33+
if(s.charAt(start++) != s.charAt(end--)) return false;
34+
}
35+
36+
return true;
37+
}
38+
}

0 commit comments

Comments
 (0)