File tree Expand file tree Collapse file tree 1 file changed +36
-0
lines changed
longest-palindromic-substring Expand file tree Collapse file tree 1 file changed +36
-0
lines changed Original file line number Diff line number Diff line change 1+ """
2+ LeetCode 5. Longest Palindromic Substring
3+ https://leetcode.com/problems/longest-palindromic-substring/
4+
5+ summary:
6+ 주어진 문자열 s에서 "가장 긴 팰린드룸 부분 문자열"을 찾아 반환
7+ """
8+
9+ class Solution :
10+ def longestPalindrome (self , s : str ) -> str :
11+
12+ # DP (시간복잡도 O(n^2), 공간복잡도 O(n^2))
13+ n = len (s )
14+ dp = [[False ]* n for _ in range (n )] # dp[i][j] = s[i..j]의 팰린드룸 여부 저장
15+ answer = ''
16+
17+ # i = 부분 문자열의 길이(1부터 n까지)
18+ for i in range (1 ,n + 1 ):
19+ # j = 부분 문자열의 시작 인덱스
20+ for j in range (n - i + 1 ):
21+ # 끝 인덱스 = 시작인덱스 + 길이 - 1
22+ end = j + i - 1
23+ # 양 끝 문자가 같을 경우
24+ if s [j ] == s [end ]:
25+ # 길이가 3이하면 팰린드룸
26+ if i <= 3 :
27+ dp [j ][end ] = True
28+ # 양 끝이 같고 안쪽도 팰린드룸이면 전체도 팰린드룸
29+ else :
30+ dp [j ][end ] = dp [j + 1 ][end - 1 ]
31+
32+ # 현재 팰린드룸의 길이가 answer보다 길면 업데이트
33+ if dp [j ][end ] and i > len (answer ):
34+ answer = s [j :end + 1 ]
35+
36+ return answer
You can’t perform that action at this time.
0 commit comments