Skip to content

Commit 4b09485

Browse files
add a solution for 5
1 parent 623c431 commit 4b09485

File tree

2 files changed

+40
-1
lines changed

2 files changed

+40
-1
lines changed

src/main/java/com/fishercoder/solutions/_5.java

Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -30,4 +30,36 @@ private void extendPalindrome(String s, int left, int right) {
3030
}
3131
}
3232
}
33+
34+
public static class Solution2 {
35+
/**
36+
* Same sliding window idea, but without using global variables.
37+
* Credit: https://leetcode.com/problems/longest-palindromic-substring/solution/
38+
*/
39+
public String longestPalindrome(String s) {
40+
int start = 0;
41+
int end = 0;
42+
for (int i = 0; i < s.length(); i++) {
43+
int len1 = expand(s, i, i);
44+
int len2 = expand(s, i, i + 1);
45+
int len = Math.max(len1, len2);
46+
if (len > end - start) {
47+
start = i - (len - 1) / 2;
48+
end = i + len / 2;
49+
}
50+
}
51+
return s.substring(start, end + 1);
52+
}
53+
54+
private int expand(String s, int left, int right) {
55+
int l = left;
56+
int r = right;
57+
while (l >= 0 && r < s.length() && s.charAt(l) == s.charAt(r)) {
58+
l--;
59+
r++;
60+
}
61+
return r - l - 1;
62+
}
63+
64+
}
3365
}

src/test/java/com/fishercoder/_5Test.java

Lines changed: 8 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -8,15 +8,22 @@
88

99
public class _5Test {
1010
private static _5.Solution1 solution1;
11+
private static _5.Solution2 solution2;
12+
private static String s;
13+
private static String expected;
1114

1215
@BeforeClass
1316
public static void setup() {
1417
solution1 = new _5.Solution1();
18+
solution2 = new _5.Solution2();
1519
}
1620

1721
@Test
1822
public void test1() {
19-
assertEquals("bab", solution1.longestPalindrome("babad"));
23+
s = "babad";
24+
expected = "bab";
25+
assertEquals(expected, solution1.longestPalindrome(s));
26+
assertEquals(expected, solution2.longestPalindrome(s));
2027
}
2128

2229
}

0 commit comments

Comments
 (0)