Skip to content

Commit a000e26

Browse files
committed
feat(soobing): week15 > longest-palindromic-substring
1 parent 1fa7e4f commit a000e26

File tree

1 file changed

+31
-0
lines changed

1 file changed

+31
-0
lines changed
Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,31 @@
1+
/**
2+
* 문제 설명
3+
* - 주어진 문자열에서 가장긴 palindromic substring을 찾는 문제
4+
*
5+
* 아이디어
6+
* 1) palindrom을 찾는 법(중심 확장법) + 홀수ver, 짝수ver 두 가지 경우를 모두 확인
7+
* - two pointer 기법을 이용하여 확장하면서 가장 긴 palindromic substring을 찾는다.
8+
*/
9+
function longestPalindrome(s: string): string {
10+
let maxLength = 0;
11+
let start = 0;
12+
13+
const expand = (l: number, r: number) => {
14+
while (l >= 0 && r < s.length && s[l] === s[r]) {
15+
const currentLength = r - l + 1;
16+
if (currentLength > maxLength) {
17+
maxLength = currentLength;
18+
start = l;
19+
}
20+
l--;
21+
r++;
22+
}
23+
};
24+
25+
for (let i = 0; i < s.length; i++) {
26+
expand(i, i);
27+
expand(i, i + 1);
28+
}
29+
30+
return s.slice(start, start + maxLength);
31+
}

0 commit comments

Comments
 (0)