File tree Expand file tree Collapse file tree 2 files changed +44
-0
lines changed
main/java/s0005.longest.palindromic.substring
test/java/s0005.longest.palindromic.substring Expand file tree Collapse file tree 2 files changed +44
-0
lines changed Original file line number Diff line number Diff line change 1+ package s0005 .longest .palindromic .substring ;
2+
3+ public class Solution {
4+ public String longestPalindrome (String s ) {
5+ int start = 0 , end = 0 ;
6+ char [] cs = s .toCharArray ();
7+ for (int i = 0 , max = 0 , prev = 0 ; i < cs .length ; ++i ) {
8+ if (i - max - 1 >= 0 && cs [i - max - 1 ] == cs [i ]
9+ && (prev == i - 1 || isPalindrome (cs , i - max , i ))) {
10+ start = i - max - 1 ;
11+ end = i + 1 ;
12+ max += 2 ;
13+ prev = i ;
14+ } else if (isPalindrome (cs , i - max , i + 1 )) {
15+ start = i - max ;
16+ end = i + 1 ;
17+ ++max ;
18+ prev = i ;
19+ }
20+ }
21+ return s .substring (start , end );
22+ }
23+
24+ private static boolean isPalindrome (char [] cs , int start , int end ) {
25+ for (int i = start , j = end - 1 ; i < j ; ++i , --j ) {
26+ if (cs [i ] != cs [j ]) {
27+ return false ;
28+ }
29+ }
30+ return true ;
31+ }
32+ }
Original file line number Diff line number Diff line change 1+ package s0005 .longest .palindromic .substring ;
2+
3+ import static org .hamcrest .CoreMatchers .equalTo ;
4+ import static org .hamcrest .MatcherAssert .assertThat ;
5+ import org .junit .Test ;
6+
7+ public class SolutionTest {
8+ @ Test
9+ public void longestPalindrome () {
10+ assertThat (new Solution ().longestPalindrome ("babad" ), equalTo ("bab" ));
11+ }
12+ }
You can’t perform that action at this time.
0 commit comments