Longest Palindromic Substring - LeetCode

Level up your coding skills and quickly land a job. This is the best place to expand your knowledge and get prepared for your next interview.

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(start, end):
        # start 와 end 가 범위를 벗어나지 않고, 펠린드롬을 충족하면
        # s[start] == s[end] 를 조건문 앞에다 두면 indexError 
            while start >= 0 and end < len(s) and s[start] == s[end]:
                start -= 1
                end += 1
            return s[start + 1: end]
 
        if len(s) < 2 or s == s[::-1]:
            return s
 
        result = ''
        for i in range(len(s) - 1):
            two_size = expand(i, i + 1)
            three_size = expand(i, i + 2)
            result = max(result, two_size, three_size, key=len)
 
        return result
cs

1.
Input: s = "babad"
Output: "bab"

6번째 줄에서 indexError 주의할 것
마지막 i에서는 three_size는 end < len(s) 조건문을 충족하지 못한다, 이 때는 two_size만 판별
2.
작동과정:
str = '123454320'
three_size 가 454를 찾았다고 가정하면, start -= 1, end += 1
34543으로 증가
....
return s[start + 1: end]에서 슬라이싱은 이상, 미만의 범위라는 것을 헷갈리면 안된다.

'알고리즘 문제풀이 with 파이썬 > LeetCode' 카테고리의 다른 글

[배열] 3Sum  (0) 2021.09.09
[배열] Trapping Rain Water  (0) 2021.09.05
[배열] Two Sum  (0) 2021.09.04
[문자열] Group Anagrams  (0) 2021.09.01
[문자열] Valid Palindrome  (0) 2021.08.30

+ Recent posts