LeetCode - Blind 75 - Longest Palindromic Substring

The Problem Given a string s, return the longest palindromic substring in s. A string is palindromic if it reads the same forward and backward. Examples Input: s = "babad" Output: "bab" Explanation: "aba" is also a valid answer. Input: s = "cbbd" Output: "bb" Constraints 1 <= s.length <= 1000 s consists of only digits and English letters. Brute Force Solution func longestPalindrome(_ s: String) -> String { let sArray = Array(s) var res = "" var resLen = 0 let n = s.count for i in 0 ..< n { for j in i ..< n { var l = i var r = j while l < r && sArray[l] == sArray[r] { l += 1 r -= 1 } if l >= r && resLen < (j - i + 1) { res = String(sArray[i ..< j + 1]) resLen = j - i + 1 } } } return res } Explanation In the first example, we are given the input "babad". Let’s visualize it and try to find the longest palindromic substring. ...

March 19, 2025 · 4 min · Dmytro Chumakov