File tree Expand file tree Collapse file tree
longest-palindromic-substring Expand file tree Collapse file tree Original file line number Diff line number Diff line change 1+ class Solution :
2+ def is_palindrome (self , s : str ) -> bool :
3+ return s == s [::- 1 ]
4+
5+ def longestPalindrome (self , s : str ) -> str :
6+ """
7+ - Idea: 아래의 방법으로 주어진 문자열에서 가장 긴 팰린드롬을 찾는다.
8+ 1. 모든 가능한 부분 문자열 생성
9+ 2. 각 부분 문자열이 팰린드롬인지 확인
10+ 3. 가장 긴 팰린드롬을 저장하고 반환
11+ - Time Complexity: O(n^3). n은 문자열의 길이
12+ 모든 부분 문자열을 구하는데 O(n^2), 각 부분 문자열이 팰린드롬인지 알아내는데 O(n).
13+ 결국 O(n^3)의 시간이 소요된다.
14+ - Space Complexity: O(n). n은 문자열의 길이
15+ 팰린드롬인지 확인할 때 문자열 슬라이싱을 사용하는데,
16+ 최악의 경우 부분 문자열의 길이가 입력 문자열의 길이와 같아
17+ 공간 복잡도는 O(n)이다.
18+ """
19+
20+ result = s [0 ]
21+
22+ for i in range (len (s ) - 1 ):
23+ for j in range (i + 1 , len (s ) + 1 ):
24+ if j - i <= len (result ):
25+ continue
26+
27+ if self .is_palindrome (s [i :j ]) and (j - i ) > len (result ):
28+ result = s [i :j ]
29+
30+ return result
You can’t perform that action at this time.
0 commit comments