File tree 2 files changed +38
-0
lines changed 2 files changed +38
-0
lines changed Original file line number Diff line number Diff line change 10
10
2|[ Add Two Numbers] ( ./0002-add-two-numbers.js ) |Medium|
11
11
3|[ Longest Substring Without Repeating Characters] ( ./0003-longest-substring-without-repeating-characters.js ) |Medium|
12
12
4|[ Median of Two Sorted Arrays] ( ./0004-median-of-two-sorted-arrays.js ) |Hard|
13
+ 5|[ Longest Palindromic Substring] ( ./0005-longest-palindromic-substring.js ) |Medium|
13
14
6|[ ZigZag Conversion] ( ./0006-zigzag-conversion.js ) |Medium|
14
15
7|[ Reverse Integer] ( ./0007-reverse-integer.js ) |Easy|
15
16
8|[ String to Integer (atoi)] ( ./0008-string-to-integer-atoi.js ) |Medium|
Original file line number Diff line number Diff line change
1
+ /**
2
+ * 5. Longest Palindromic Substring
3
+ * https://leetcode.com/problems/longest-palindromic-substring/
4
+ * Difficulty: Medium
5
+ *
6
+ * Given a string `s`, return the longest palindromic substring in `s`.
7
+ */
8
+
9
+ /**
10
+ * @param {string } s
11
+ * @return {string }
12
+ */
13
+ var longestPalindrome = function ( s ) {
14
+ let result = '' ;
15
+
16
+ for ( let i = 0 ; i < s . length ; i ++ ) {
17
+ let palindrome1 = getExtendedPalindrome ( s , i , i ) ;
18
+ let palindrome2 = getExtendedPalindrome ( s , i , i + 1 ) ;
19
+ let longerPalindrome = palindrome1 . length > palindrome2 . length
20
+ ? palindrome1 : palindrome2 ;
21
+
22
+ if ( longerPalindrome . length > result . length ) {
23
+ result = longerPalindrome ;
24
+ }
25
+ }
26
+
27
+ return result ;
28
+ } ;
29
+
30
+ function getExtendedPalindrome ( s , start , end ) {
31
+ while ( start >= 0 && end < s . length && s [ start ] === s [ end ] ) {
32
+ start -- ;
33
+ end ++ ;
34
+ }
35
+
36
+ return s . slice ( start + 1 , end ) ;
37
+ }
You can’t perform that action at this time.
0 commit comments