File tree Expand file tree Collapse file tree 1 file changed +29
-0
lines changed Expand file tree Collapse file tree 1 file changed +29
-0
lines changed Original file line number Diff line number Diff line change
1
+ class Solution {
2
+ // O(N^2) time, O(1) space
3
+ public String longestPalindrome (String s ) {
4
+ if (s == null || s .length () < 1 ) return "" ;
5
+ int start = 0 ;
6
+ int end = 0 ;
7
+ for (int i =0 ; i <s .length (); i ++) {
8
+ int len1 = expandFromCentre (s , i , i ); //"racecar" for 'e'
9
+ int len2 = expandFromCentre (s , i , i +1 ); //babaabab
10
+
11
+ int max_len = Math .max (len1 , len2 );
12
+ if (max_len > end - start ) {
13
+ start = i - ((max_len - 1 )/2 );
14
+ end = i + (max_len /2 );
15
+ }
16
+ }
17
+ return s .substring (start , end +1 );
18
+ }
19
+
20
+ public int expandFromCentre (String s , int left , int right ) {
21
+ if (s == null || left > right ) return 0 ;
22
+
23
+ while (left >= 0 && right < s .length () && s .charAt (left ) == s .charAt (right )) {
24
+ left --;
25
+ right ++;
26
+ }
27
+ return right - left - 1 ;
28
+ }
29
+ }
You can’t perform that action at this time.
0 commit comments