File tree 1 file changed +45
-0
lines changed
longest-palindromic-substring
1 file changed +45
-0
lines changed Original file line number Diff line number Diff line change
1
+ /**
2
+ * 중심 확장법을 이용하여 가장 긴 팰린드롬 찾기
3
+ * 알고리즘 복잡도
4
+ * - 시간 복잡도: O(n2)
5
+ * - 공간 복잡도: O(1)
6
+ * @param s
7
+ */
8
+ function longestPalindrome ( s : string ) : string {
9
+ let maxLength = 0 ;
10
+ let longestPal = '' ;
11
+
12
+ for ( let x = 0 ; x < s . length ; x ++ ) {
13
+ // 1. 홀수 길이 팰린드롬 - 한 문자를 중심으로 함
14
+ let left = x
15
+ let right = x
16
+
17
+ while ( left >= 0 && right < s . length && s [ left ] === s [ right ] ) {
18
+ // 현재 발견한 팰린드롬이 이전에 발견한 것보다 길면 갱신
19
+ if ( right - left + 1 > maxLength ) {
20
+ maxLength = right - left + 1 ;
21
+ longestPal = s . substring ( left , right + 1 ) ;
22
+ }
23
+
24
+ left --
25
+ right ++
26
+ }
27
+
28
+ // 2. 짝수 길이 팰린드롬 - 두 문자 사이를 중심으로 함
29
+ left = x
30
+ right = x + 1
31
+
32
+ while ( left >= 0 && right < s . length && s [ left ] === s [ right ] ) {
33
+ // 현재 발견한 팰린드롬이 이전에 발견한 것보다 길면 갱신
34
+ if ( right - left + 1 > maxLength ) {
35
+ maxLength = right - left + 1 ;
36
+ longestPal = s . substring ( left , right + 1 ) ;
37
+ }
38
+
39
+ left --
40
+ right ++
41
+ }
42
+ }
43
+
44
+ return longestPal
45
+ }
You can’t perform that action at this time.
0 commit comments