[Leetcode] 5. Longest Palindromic Substring
[Leetcode] 5. Longest Palindromic Substring

[Leetcode] 5. Longest Palindromic Substring

์–ธ์–ด
Python
C
๋‚œ์ด๋„
๋‹ค์‹œ ํ’€์–ด๋ณด๊ธฐ
๋‹ค์‹œ ํ’€์–ด๋ณด๊ธฐ
์•Œ๊ณ ๋ฆฌ์ฆ˜ ์œ ํ˜•
์ž‘์„ฑ์ž
๋ฐ•์šฉ์„ฑ๋ฐ•์šฉ์„ฑ
์ƒ์„ฑ ์ผ์‹œ
2024๋…„ 06์›” 03์ผ

๐Ÿ–ฅ๏ธย ์‹œ์ž‘ํ•˜๋ฉฐ

์ฃผ์–ด์ง„ ๋ฌธ์ž์—ด์—์„œ ๊ฐ€์žฅ ๊ธด ํŒฐ๋ฆฐ๋“œ๋กฌ ๋ถ€๋ถ„ ๋ฌธ์ž์—ด์„ ์ฐพ์•„์•ผ ํ•ฉ๋‹ˆ๋‹ค. ์•ž์—์„œ ์ฝ์–ด๋„, ๋’ค์—์„œ ์ฝ์–ด๋„ ๊ฐ™์€ ๋ฌธ์ž์—ด์„ ๋œปํ•ฉ๋‹ˆ๋‹ค.
ย 
์ด ๋ฌธ์ œ๋ฅผ ํ•ด๊ฒฐํ•˜๊ธฐ ์œ„ํ•ด ์ค‘์•™์„ ๊ธฐ์ค€์œผ๋กœ ํŒฐ๋ฆฐ๋“œ๋กฌ์„ ํ™•์žฅํ•ด ๋‚˜๊ฐ€๋Š” ๋ฐฉ๋ฒ•์„ ์‚ฌ์šฉํ–ˆ์Šต๋‹ˆ๋‹ค.
ย 
  1. ํŒฐ๋ฆฐ๋“œ๋กฌ ํ™•์žฅ ํ•จ์ˆ˜ ์ •์˜:
      • calc(left: int, right: int) -> str : ์ฃผ์–ด์ง„ ์ธ๋ฑ์Šค left ์™€ right ๋ฅผ ์ค‘์‹ฌ์œผ๋กœ ํŒฐ๋ฆฐ๋“œ๋กฌ์„ ํ™•์žฅํ•ด ๋‚˜๊ฐ‘๋‹ˆ๋‹ค. left ์™€ right ๋Š” ๊ฐ๊ฐ ์ค„์–ด๋“ค๊ณ  ๋Š˜์–ด๋‚ฉ๋‹ˆ๋‹ค.
  1. ํŒฐ๋ฆฐ๋“œ๋กฌ ํƒ์ƒ‰:
      • ๋ฌธ์ž์—ด s ์˜ ๊ฐ ๋ฌธ์ž๋ฅผ ์ค‘์‹ฌ์œผ๋กœ ํŒฐ๋ฆฐ๋“œ๋กฌ์„ ํ™•์žฅํ•ฉ๋‹ˆ๋‹ค.
      • ๊ฐ ๋ฌธ์ž i ์— ๋Œ€ํ•ด ํ™€์ˆ˜ ๊ธธ์ด ํŒฐ๋ฆฐ๋“œ๋กฌ๊ณผ ์ง์ˆ˜ ๊ธธ์ด ํŒฐ๋ฆฐ๋“œ๋กฌ์„ ์ฒดํฌํ•ฉ๋‹ˆ๋‹ค. ๋‘˜์˜ ๊ตฌ์กฐ๊ฐ€ ๋‹ค๋ฅด๊ธฐ ๋•Œ๋ฌธ์ž…๋‹ˆ๋‹ค.
      • calc(i, i) : ํ™€์ˆ˜ ๊ธธ์ด ํŒฐ๋ฆฐ๋“œ๋กฌ ์ฒดํฌํ•ฉ๋‹ˆ๋‹ค.
      • calc(i, i + 1) : ์ง์ˆ˜ ๊ธธ์ด ํŒฐ๋ฆฐ๋“œ๋กฌ ์ฒดํฌํ•ฉ๋‹ˆ๋‹ค.
ย 

โš™๏ธย Python

from typing import List class Solution: def longestPalindrome(self, s: str) -> str: # ์ค‘์•™์—์„œ๋ถ€ํ„ฐ ์•ž๋’ค๋กœ ํŒฐ๋ฆฐ๋“œ๋กฌ ์ฒดํฌ def calc(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) == 0: return "" longest = "" for i in range(len(s)): # ํ™€์ˆ˜ ํŒฐ๋ฆฐ๋“œ๋กฌ ์ฒดํฌ odd = calc(i, i) if len(odd) > len(longest): longest = odd # ์ง์ˆ˜ ํŒฐ๋ฆฐ๋“œ๋กฌ ์ฒดํฌ even = calc(i, i + 1) if len(even) > len(longest): longest = even return longest # ์˜ˆ์ œ ํ…Œ์ŠคํŠธ sol = Solution() print(sol.longestPalindrome("babad")) print(sol.longestPalindrome("cbbd"))
ย 

๐Ÿ“Œย ์†Œ๊ฐ

์˜ค๋žœ๋งŒ์— ๋ฌธ์ž์—ด์„ ๋‹ค๋ค„๋ณธ ๋ฌธ์ œ์˜€์Šต๋‹ˆ๋‹ค.

๋Œ“๊ธ€

guest