-
[Leetcode] 5. Longest palindromic substring (Typescript)Algorithm 2022. 2. 1. 16:37728x90
Given a string s, return the longest palindromic substring in s.
Example 1:
Input: s = "babad" Output: "bab" Explanation: "aba" is also a valid answer.
Example 2:
Input: s = "cbbd" Output: "bb"
Constraints:
- 1 <= s.length <= 1000
- s consist of only digits and English letters.
const longestPalindrome = (s: string) => { const checkPalindrome = (lIndex: number, rIndex: number) => { while (lIndex >= 0 && rIndex <= s.length && s[lIndex] === s[rIndex - 1]) { --lIndex; ++rIndex; } return s.substring(lIndex + 1, rIndex - 1); }; if (s.length < 2 || s === s.split('').reverse().join('')) return s; return s.split('').reduce((longestPalindrome, cur, i) => { const evenPalindrome = checkPalindrome(i, i + 1); const oddPalindrome = checkPalindrome(i, i + 2); const values = [longestPalindrome, evenPalindrome, oddPalindrome]; return values.sort((a, b) => b.length - a.length)[0]; }, ''); };
728x90'Algorithm' 카테고리의 다른 글
[Leetcode] 7. Reverse Integer Typescript (0) 2022.08.25 [Leetcode] 6. Zigzag Conversion Typescript (0) 2022.08.25 [leetcode] 4. Median of Two Sorted Arrays (Typescript) (0) 2021.02.21 [leetcode] 3. Longest Substring Without Repeating Characters (Typescript) (0) 2021.02.20 [Algorithm] Sliding Window 알고리즘 (Javascript) (0) 2021.02.14