728x90
5. Longest Palindromic Substring
Given a string s
, return the longest palindromic substring in s
.
Example
1:
Input: s = "babad"
Output: "bab"
Note: "aba" is also a valid answer.
2:
Input: s = "cbbd"
Output: "bb"
3:
Input: s = "a"
Output: "a"
4:
Input: s = "ac"
Output: "a"
Constraints:
1 <= s.length <= 1000
s
consist of only digits and English letters.
Python solution
class Solution:
def longestPalindrome(self, s: str) -> str:
if len(s) <= 1:
return s
i = l = 0
for j in range(len(s)):
if s[j-l: j+1] == s[j-l: j+1][::-1]:
i = j-l
l += 1
elif j-l > 0 and s[j-l-1: j+1] == s[j-l-1: j+1][::-1]:
i = j-l-1
l += 2
return s[i: i+l]
Accepted 104ms runtime
728x90
'알고리즘 > LeetCode' 카테고리의 다른 글
[Python] Median of Two Sorted Arrays - LeetCode (0) | 2021.09.16 |
---|---|
[Python] Longest Substring Without Repeating Characters - LeetCode (0) | 2021.09.16 |
[Python] Add Two Numbers - LeetCode (0) | 2021.09.16 |
[Python] Two Sum - LeetCode (0) | 2021.09.16 |
댓글