File tree Expand file tree Collapse file tree 1 file changed +39
-0
lines changed
LeetCode/Algorithms/Medium/LongestPalindromicSubstring Expand file tree Collapse file tree 1 file changed +39
-0
lines changed Original file line number Diff line number Diff line change 1+ public class LongestPallindromicSubstring {
2+
3+ public String longestPalindrome (String s ) {
4+ if (s == null || s .length () < 1 ) return "" ;
5+ int start = 0 ;
6+ int end = 0 ;
7+
8+ for (int i = 0 ; i < s .length (); i ++) {
9+ int len1 = expandFromMiddle (s , i , i ); // racecar
10+ int len2 = expandFromMiddle (s , i , i + 1 ); // abba
11+ int len = Math .max (len1 , len2 );
12+ if (len > end - start ) {
13+ start = i - ((len - 1 ) / 2 );
14+ end = i + (len / 2 );
15+ }
16+ }
17+ return s .substring (start , end + 1 );
18+ }
19+
20+ // racecar
21+ // 0123456
22+ // i = 3
23+ // len1 = 7
24+ // start = 3 - (7-1/2) = 0
25+ // end = 3 + 7/2 = 3 + 3 = 6
26+
27+ public int expandFromMiddle (String s , int left , int right ) {
28+ if (s == null || left > right )
29+ return 0 ;
30+
31+ while (left >= 0 && right < s .length () &&
32+ s .charAt (left ) == s .charAt (right )) {
33+ left --;
34+ right ++;
35+ }
36+ return right - left - 1 ; // -1 for that extra right++ increment in while loop
37+ }
38+ }
39+
You can’t perform that action at this time.
0 commit comments