File tree Expand file tree Collapse file tree 1 file changed +42
-0
lines changed Expand file tree Collapse file tree 1 file changed +42
-0
lines changed Original file line number Diff line number Diff line change
1
+ class Solution {
2
+
3
+ //Time: O(n^2), where n is s length
4
+ //Space: O(1)
5
+ public String longestPalindrome (String s ) {
6
+
7
+ String longestPal = "" ;
8
+
9
+ for (int i = 0 ; i < s .length (); i ++) {
10
+ int offset1 = expandOffset (s , i , i );
11
+ int offset2 = expandOffset (s , i , i + 1 );
12
+
13
+ String subs = "" ;
14
+
15
+ int maxOffset = Math .max (offset1 , offset2 );
16
+
17
+ if (offset2 > offset1 ) {
18
+ subs = s .substring (i - maxOffset + 1 , i + maxOffset + 1 );
19
+ } else {
20
+ subs = s .substring (i - maxOffset , i + maxOffset + 1 );
21
+ }
22
+
23
+ if (longestPal .length () < subs .length ()) longestPal = subs ;
24
+
25
+ }
26
+
27
+ return longestPal ;
28
+
29
+ }
30
+
31
+ private int expandOffset (String s , int left , int right ) {
32
+
33
+ while (left >= 0 && right < s .length () && s .charAt (left ) == s .charAt (right )) {
34
+ left --;
35
+ right ++;
36
+ }
37
+
38
+ return (right - left - 1 ) / 2 ;
39
+
40
+ }
41
+
42
+ }
You can’t perform that action at this time.
0 commit comments