Leetcode Problem 5. Longest Palindromic Substring

5. Longest Palindromic Substring

Leetcode Solutions

Approach: Expand From Centers

  1. Define a helper method expand that takes two indices left and right and expands outwards while s[left] == s[right].
  2. Initialize ans to store the bounds of the longest palindrome found.
  3. Iterate over each index i in the string s. a. Call expand(i, i) to find the longest odd-length palindrome centered at i. b. Update ans if a longer palindrome is found. c. Call expand(i, i + 1) to find the longest even-length palindrome centered at i and i + 1. d. Update ans if a longer palindrome is found.
  4. After iterating through all centers, use ans to return the longest palindromic substring.
UML Thumbnail

Approach: Check All Substrings

Ask Question

Programming Language
image/screenshot of info(optional)
Full Screen
Loading...

Suggested Answer

Answer
Full Screen
Copy Answer Code
Loading...