Movatterモバイル変換


[0]ホーム

URL:


Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit90f9a00

Browse files
add a solution for 5
1 parent4ce5910 commit90f9a00

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
returnr -l -1;
6262
}
63+
}
64+
65+
publicstaticclassSolution3 {
66+
/**
67+
* My own implementation using the same idea.
68+
*/
69+
publicStringlongestPalindrome(Strings) {
70+
Stringans ="";
71+
intmaxLen =0;
72+
for (inti =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+
returnans;
85+
}
86+
87+
privateint[]expand(Strings,intl,intr) {
88+
int[]pair =newint[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+
returnpair;
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
publicclass_5Test {
1010
privatestatic_5.Solution1solution1;
1111
privatestatic_5.Solution2solution2;
12+
privatestatic_5.Solution3solution3;
1213
privatestaticStrings;
1314

1415
@BeforeClass
1516
publicstaticvoidsetup() {
1617
solution1 =new_5.Solution1();
1718
solution2 =new_5.Solution2();
19+
solution3 =new_5.Solution3();
1820
}
1921

2022
@Test
2123
publicvoidtest1() {
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)

[8]ページ先頭

©2009-2025 Movatter.jp