-
Notifications
You must be signed in to change notification settings - Fork 38
Expand file tree
/
Copy pathPalindromePartition.java
More file actions
34 lines (32 loc) · 972 Bytes
/
PalindromePartition.java
File metadata and controls
34 lines (32 loc) · 972 Bytes
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
class Solution {
public List<List<String>> partition(String s) {
List<List<String>> result = new ArrayList<>();
backtrack(result, s, new ArrayList<String>(), 0);
return result;
}
public void backtrack(List<List<String>> result, String s, List<String> temp, int start)
{
if(start == s.length())
result.add(new ArrayList<String>(temp));
else
{
for(int i=start; i<s.length(); i++)
{
if(isPalindrome(s, start, i))
{
temp.add(s.substring(start, i+1));
backtrack(result, s, temp, i+1);
temp.remove(temp.size()-1);
}
}
}
}
public boolean isPalindrome(String s, int left, int right)
{
while(left < right)
{
if(s.charAt(left++) != s.charAt(right--)) return false;
}
return true;
}
}