Skip to content

Commit bbb8f4e

Browse files
committed
Add problem 131
1 parent 3cd429e commit bbb8f4e

File tree

1 file changed

+101
-0
lines changed

1 file changed

+101
-0
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,101 @@
1+
package io.github.juchanei.leetcodeJava;
2+
3+
import org.junit.Assert;
4+
import org.junit.Test;
5+
6+
import java.util.ArrayList;
7+
import java.util.Arrays;
8+
import java.util.List;
9+
import java.util.stream.Collectors;
10+
import java.util.stream.Stream;
11+
12+
public class PalindromePartitioning {
13+
public List<List<String>> partition(String s) {
14+
if (s.length() == 0) {
15+
return List.of(List.of());
16+
}
17+
18+
List<List<String>> ret = new ArrayList<>();
19+
for (int i = 0; i <= s.length(); i++) {
20+
String candidate = s.substring(0, i);
21+
22+
if (!isPalindrome(candidate)) continue;
23+
24+
partition(s.substring(i))
25+
.stream()
26+
.map(strings -> Stream
27+
.concat(Stream.of(candidate), strings.stream())
28+
.collect(Collectors.toList()))
29+
.forEach(strings -> ret.add(strings));
30+
}
31+
32+
return ret;
33+
}
34+
35+
public boolean isPalindrome(String candidate) {
36+
int length = candidate.length();
37+
if (length == 0) return false;
38+
if (length == 1) return true;
39+
40+
for (int i = 0; i < (length / 2); i++)
41+
if (candidate.charAt(i) != candidate.charAt(length - 1 - i))
42+
return false;
43+
44+
return true;
45+
}
46+
47+
48+
public static class UnitTest {
49+
private PalindromePartitioning pp = new PalindromePartitioning();
50+
51+
@Test
52+
public void example1() {
53+
String input = "aab";
54+
List<List<String>> output = Arrays.asList(
55+
Arrays.asList("a","a","b"),
56+
Arrays.asList("aa","b")
57+
);
58+
59+
Assert.assertArrayEquals(
60+
output.toArray(),
61+
pp.partition(input).toArray()
62+
);
63+
}
64+
65+
@Test
66+
public void example2() {
67+
String input = "a";
68+
List<List<String>> output = Arrays.asList(
69+
Arrays.asList("a")
70+
);
71+
72+
Assert.assertArrayEquals(
73+
output.toArray(),
74+
pp.partition(input).toArray()
75+
);
76+
}
77+
78+
@Test
79+
public void palindromeTest() {
80+
Assert.assertEquals(true, pp.isPalindrome("heleh"));
81+
Assert.assertEquals(true, pp.isPalindrome("h"));
82+
Assert.assertEquals(true, pp.isPalindrome("hh"));
83+
Assert.assertEquals(false, pp.isPalindrome("ddheleh"));
84+
Assert.assertEquals(false, pp.isPalindrome(""));
85+
}
86+
87+
@Test
88+
public void test1() {
89+
String input = "bb";
90+
List<List<String>> output = Arrays.asList(
91+
Arrays.asList("b", "b"),
92+
Arrays.asList("bb")
93+
);
94+
95+
Assert.assertArrayEquals(
96+
output.toArray(),
97+
pp.partition(input).toArray()
98+
);
99+
}
100+
}
101+
}

0 commit comments

Comments
 (0)