알고리즘
8. 가장 긴 팰린드롬 부분 문자열(투포인터, 슬라이딩 윈도우,max)
jwjwvison
2021. 8. 18. 00:03
https://leetcode.com/problems/longest-palindromic-substring/
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
가장 긴 팰린드롬 부분 문자열을 출력하라.
개인적으로 상당히 까다로웠다고 생각되었던 문제이다.
이 문제로 투포인터, 슬라이딩 윈도우, 조건부 max() 함수에 대해서 정확히 이해할 수 있게 되어서 포스팅에 올리겠다.
이 문제의 핵심 포인트는 슬라이딩 윈도우하는 투포인터를 각각 함수를 통해 결과값을 도출한뒤 max()함수로 조건을 길이로 제시해 값을 얻어내는 부분이다.
class Solution:
def longestPalindrome(self, s: str) -> str:
def check(word,start,end):
if start<0 or end>len(word):
return ''
s=word[start:end]
if s==s[::-1]:
while True:
start-=1
end+=1
s=word[start:end]
if start<0 or end>len(word) or s!=s[::-1]:
start+=1
end-=1
break
else:
continue
else:
return ''
return word[start:end]
res=s[0]
if len(s)<2 or s==s[::-1]:
return s
else:
for i in range(len(s)):
res=(max(check(s,i,i+3),check(s,i,i+2),res,key=len))
return res