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.
Table of Contents
Solution
class Solution:
def longestPalindrome(self, s):
"""
:type s: str
:rtype: str
"""
# Return if string is empty
if not s: return s
res = ""
for i in range(len(s)):
j = i + 1
# While j is less than length of string
# AND res is *not* longer than substring s[i:]
while j <= len(s) and len(res) <= len(s[i:]):
# If substring s[i:j] is a palindrome
# AND substring is longer than res
if s[i:j] == s[i:j][::-1] and len(s[i:j]) > len(res):
res = s[i:j]
j += 1
return res
class Solution:
def longestPalindrome(self, s):
"""
:type s: str
:rtype: str
"""
# Return if string is empty
if not s: return s
res = ""
for i in range(len(s)):
j = i + 1
# While j is less than length of string
# AND res is *not* longer than substring s[i:]
while j <= len(s) and len(res) <= len(s[i:]):
# If substring s[i:j] is a palindrome
# AND substring is longer than res
if s[i:j] == s[i:j][::-1] and len(s[i:j]) > len(res):
res = s[i:j]
j += 1
return res