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"
Solution:
# @param {String} s
# @return {String}
def expand_around_center(s, left_idx, right_idx)
while left_idx >= 0 && right_idx < s.length && s[left_idx] == s[right_idx]
left_idx -= 1
right_idx +=1
end
s[left_idx + 1...right_idx]
end
def longest_palindrome(s)
return s if s.empty?
longest = ""
(0...s.length).each do |i|
odd_palindrome = expand_around_center(s, i, i)
even_palindrome = expand_around_center(s, i, i + 1)
longest = odd_palindrome if longest.length < odd_palindrome.length
longest = even_palindrome if longest.length < even_palindrome.length
end
longest
end
Share this post
Related Posts
Jump Game II
April 13, 2025
Generate Parentheses
April 03, 2025
Choosing pivot in Quicksort
April 14, 2025