-
Notifications
You must be signed in to change notification settings - Fork 17
/
Copy pathPalindromePartitioning.java
43 lines (35 loc) · 1.05 KB
/
PalindromePartitioning.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
class Solution {
public List<List<String>> partition(String s) {
List<List<String>> list = new ArrayList <>();
List <String> ans = new ArrayList<>();
partition(s, ans, list);
return list;
}
static void partition(String ques, List<String> ans, List<List<String>> list) {
if(ques.length() == 0) {
list.add(new ArrayList<>(ans));
return;
}
for(int i=1 ; i<=ques.length(); i++) {
String nq = ques.substring(i);
String comp = ques.substring(0,i);
if(palindrome(comp)) {
ans.add(comp);
partition(nq, ans, list);
ans.remove(ans.size()-1);
}
}
}
static boolean palindrome(String str) {
int i = 0;
int j = str.length() - 1;
while(i < j) {
if(str.charAt(i) != str.charAt(j)) {
return false;
}
i++;
j--;
}
return true;
}
}