-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path131. Palindrome Partitioning.java
51 lines (44 loc) · 1.25 KB
/
131. Palindrome Partitioning.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
44
45
46
47
48
49
50
51
class Solution {
public List<List<String>> partition(String s) {
List<List<String>> res = new ArrayList<>();
ArrayList<String> list = new ArrayList<>();
solution(s, res, list);
return res;
}
public void solution(String s, List<List<String>> res, ArrayList<String> list)
{
if(s.length() == 0)
{
ArrayList<String> l = new ArrayList<>(list);
// Collections.sort(l);
res.add(l);
return;
}
for(int i = 0; i < s.length(); i++)
{
String prefix = s.substring(0, i+1);
String ros = s.substring(i+1);
if(isPalindromic(prefix))
{
list.add(prefix);
solution(ros, res, list);
list.remove(list.size() - 1);
}
}
}
public boolean isPalindromic(String str)
{
int left = 0;
int right = str.length() - 1;
while(left < right)
{
char l = str.charAt(left);
char r = str.charAt(right);
if(l != r)
return false;
left++;
right--;
}
return true;
}
}