Skip to content

Commit d68d1d9

Browse files
committed
feat: longest-palindromic-substring solution
1 parent e623f67 commit d68d1d9

File tree

1 file changed

+45
-0
lines changed

1 file changed

+45
-0
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,45 @@
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+
}

0 commit comments

Comments
 (0)