File tree 1 file changed +31
-0
lines changed
longest-palindromic-substring
1 file changed +31
-0
lines changed Original file line number Diff line number Diff line change
1
+ // Time Complexity: O(n^2)
2
+ // Space Complexity: O(1)
3
+
4
+ var longestPalindrome = function ( s ) {
5
+ let start = 0 ,
6
+ maxLength = 1 ;
7
+
8
+ // to expand around the center and update the start and maxLength
9
+ function expandAroundCenter ( left , right ) {
10
+ while ( left >= 0 && right < s . length && s [ left ] === s [ right ] ) {
11
+ left -- ;
12
+ right ++ ;
13
+ }
14
+ // update the start and maxLength if a longer palindrome is found
15
+ if ( maxLength < right - left - 1 ) {
16
+ start = left + 1 ;
17
+ maxLength = right - left - 1 ;
18
+ }
19
+ }
20
+
21
+ // iterate through each character in the string
22
+ for ( let i = 0 ; i < s . length ; i ++ ) {
23
+ // expand around the current character
24
+ expandAroundCenter ( i , i ) ;
25
+ // expand around the current and next character
26
+ expandAroundCenter ( i , i + 1 ) ;
27
+ }
28
+
29
+ // return the longest palindromic substring
30
+ return s . substring ( start , start + maxLength ) ;
31
+ } ;
You can’t perform that action at this time.
0 commit comments