-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathPalindrome Partitioning.java
46 lines (41 loc) · 1.2 KB
/
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
// https://leetcode.com/problems/palindrome-partitioning/
class Solution {
public List<List<String>> partition(String s) {
List<List<String>> result = new ArrayList<>();
List<String> help = new ArrayList<>();
helpart(s, help, result);
return result;
}
void helpart(String s, List<String> help, List<List<String>> result)
{
if(s.length() == 1)
{
help.add(s);
result.add(new ArrayList<String>(help));
help.remove(help.size()-1);
return;
}
for(int i = 1; i < s.length(); i++)
{
if(ispal(s.substring(0,i)))
{
help.add(s.substring(0,i));
helpart(s.substring(i),help, result);
help.remove(help.size()-1);
}
}
if(ispal(s))
{
help.add(s);
result.add(new ArrayList<String>(help));
help.remove(help.size()-1);
}
}
boolean ispal(String st)
{
if(st.length() == 1) return true;
StringBuffer sbr = new StringBuffer(st);
sbr.reverse();
return st.equals(sbr.toString());
}
}