File tree Expand file tree Collapse file tree 1 file changed +31
-0
lines changed
longest-palindromic-substring Expand file tree Collapse file tree 1 file changed +31
-0
lines changed Original file line number Diff line number Diff line change
1
+ // TC: O(n^2)
2
+ // for loop & nested while loop => total O(n^2)
3
+ // SC: O(1)
4
+ // uses only constant space => O(1)
5
+ class Solution {
6
+ public String longestPalindrome (String s ) {
7
+ int right = 0 ;
8
+ int left = 0 ;
9
+
10
+ for (int i = 0 ; i < s .length (); i ++) {
11
+ int even = pad (s , i , i );
12
+ int odd = pad (s , i , i +1 );
13
+ int max = Math .max (even , odd );
14
+
15
+ if (max > (right - left )) {
16
+ right = i + (max + 1 ) / 2 ;
17
+ left = i - max / 2 ;
18
+ }
19
+ }
20
+
21
+ return s .substring (left , right +1 );
22
+ }
23
+
24
+ private int pad (String s , int start , int end ) {
25
+ while (start >= 0 && end < s .length () && s .charAt (start ) == s .charAt (end )) {
26
+ start -= 1 ;
27
+ end += 1 ;
28
+ }
29
+ return start - end ;
30
+ }
31
+ }
You can’t perform that action at this time.
0 commit comments