https://leetcode.com/problems/longest-palindromic-substring/description/
Longest Palindromic Substring - LeetCode
Longest Palindromic Substring - 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.le
leetcode.com
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
|
class Solution:
def longestPalindrome(self, s: str) -> str:
def expand(left: int, right: int) -> str:
while left >= 0 and right < len(s) and s[left] == s[right]:
left -= 1
right += 1
return s[left + 1:right]
if len(s) < 2 or s == s[::-1]:
return s
result = ''
for i in range(0, len(s) - 1):
result = max(result,
expand(i, i + 1),
expand(i, i + 2),
key=len)
return result
|
cs |
반응형
'python-algorithm' 카테고리의 다른 글
백준 27434 팩토리얼 3 (0) | 2023.02.09 |
---|---|
백준 27433 팩토리얼 2 (0) | 2023.02.09 |
백준 25630 팰린드롬 소떡소떡 (0) | 2023.02.08 |
leetcode 49. Group Anagrams (0) | 2023.02.07 |
leetcode 819. Most Common Word (0) | 2023.02.07 |
댓글