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

Commit4b09485

Browse files
add a solution for 5
1 parent623c431 commit4b09485

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+
publicstaticclassSolution2 {
35+
/**
36+
* Same sliding window idea, but without using global variables.
37+
* Credit: https://leetcode.com/problems/longest-palindromic-substring/solution/
38+
*/
39+
publicStringlongestPalindrome(Strings) {
40+
intstart =0;
41+
intend =0;
42+
for (inti =0;i <s.length();i++) {
43+
intlen1 =expand(s,i,i);
44+
intlen2 =expand(s,i,i +1);
45+
intlen =Math.max(len1,len2);
46+
if (len >end -start) {
47+
start =i - (len -1) /2;
48+
end =i +len /2;
49+
}
50+
}
51+
returns.substring(start,end +1);
52+
}
53+
54+
privateintexpand(Strings,intleft,intright) {
55+
intl =left;
56+
intr =right;
57+
while (l >=0 &&r <s.length() &&s.charAt(l) ==s.charAt(r)) {
58+
l--;
59+
r++;
60+
}
61+
returnr -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
publicclass_5Test {
1010
privatestatic_5.Solution1solution1;
11+
privatestatic_5.Solution2solution2;
12+
privatestaticStrings;
13+
privatestaticStringexpected;
1114

1215
@BeforeClass
1316
publicstaticvoidsetup() {
1417
solution1 =new_5.Solution1();
18+
solution2 =new_5.Solution2();
1519
}
1620

1721
@Test
1822
publicvoidtest1() {
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)

[8]ページ先頭

©2009-2025 Movatter.jp