File tree Expand file tree Collapse file tree 1 file changed +32
-0
lines changed
longest-palindromic-substring Expand file tree Collapse file tree 1 file changed +32
-0
lines changed Original file line number Diff line number Diff line change
1
+ /**
2
+ * https://leetcode.com/problems/longest-palindromic-substring
3
+ * T.C. O(n^2)
4
+ * S.C. O(1)
5
+ */
6
+ function longestPalindrome ( s : string ) : string {
7
+ if ( s . length < 2 ) return s ;
8
+ let start = 0 ;
9
+ let end = 0 ;
10
+
11
+ for ( let i = 0 ; i < s . length ; i ++ ) {
12
+ const len1 = expandBothSides ( s , i , i ) ; // odd
13
+ const len2 = expandBothSides ( s , i , i + 1 ) ; // even
14
+ const len = Math . max ( len1 , len2 ) ;
15
+
16
+ if ( len > end - start ) {
17
+ start = i - Math . floor ( ( len - 1 ) / 2 ) ;
18
+ end = i + Math . floor ( len / 2 ) ;
19
+ }
20
+ }
21
+
22
+ return s . slice ( start , end + 1 ) ;
23
+ }
24
+
25
+ function expandBothSides ( s : string , left : number , right : number ) : number {
26
+ while ( 0 <= left && right < s . length && s [ left ] === s [ right ] ) {
27
+ left -- ;
28
+ right ++ ;
29
+ }
30
+
31
+ return right - left - 1 ;
32
+ }
You can’t perform that action at this time.
0 commit comments