Skip to content

Commit 90f9a00

Browse files
add a solution for 5
1 parent 4ce5910 commit 90f9a00

File tree

2 files changed

+37
-0
lines changed

2 files changed

+37
-0
lines changed

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

Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -60,6 +60,40 @@ private int expand(String s, int left, int right) {
6060
}
6161
return r - l - 1;
6262
}
63+
}
64+
65+
public static class Solution3 {
66+
/**
67+
* My own implementation using the same idea.
68+
*/
69+
public String longestPalindrome(String s) {
70+
String ans = "";
71+
int maxLen = 0;
72+
for (int i = 0; i < s.length(); i++) {
73+
int[] pair = expand(s, i, i);
74+
if (pair[1] - pair[0] + 1 > maxLen) {
75+
maxLen = pair[1] - pair[0] + 1;
76+
ans = s.substring(pair[0], pair[1] + 1);
77+
}
78+
pair = expand(s, i, i + 1);
79+
if (pair[1] - pair[0] + 1 > maxLen) {
80+
maxLen = pair[1] - pair[0] + 1;
81+
ans = s.substring(pair[0], pair[1] + 1);
82+
}
83+
}
84+
return ans;
85+
}
86+
87+
private int[] expand(String s, int l, int r) {
88+
int[] pair = new int[2];
89+
while (l >= 0 && r < s.length() && s.charAt(l) == s.charAt(r)) {
90+
pair[0] = l;
91+
pair[1] = r;
92+
l--;
93+
r++;
94+
}
95+
return pair;
96+
}
6397

6498
}
6599
}

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

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -9,19 +9,22 @@
99
public class _5Test {
1010
private static _5.Solution1 solution1;
1111
private static _5.Solution2 solution2;
12+
private static _5.Solution3 solution3;
1213
private static String s;
1314

1415
@BeforeClass
1516
public static void setup() {
1617
solution1 = new _5.Solution1();
1718
solution2 = new _5.Solution2();
19+
solution3 = new _5.Solution3();
1820
}
1921

2022
@Test
2123
public void test1() {
2224
s = "babad";
2325
assertEquals("bab", solution1.longestPalindrome(s));
2426
assertEquals("aba", solution2.longestPalindrome(s));
27+
assertEquals("aba", solution3.longestPalindrome(s));
2528
}
2629

2730
}

0 commit comments

Comments
 (0)
pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy