Skip to content

Commit a9d406d

Browse files
committed
Add week 15 solutions: longest-palindromic-substring/
1 parent a76bdc4 commit a9d406d

File tree

1 file changed

+45
-0
lines changed

1 file changed

+45
-0
lines changed
Lines changed: 45 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,45 @@
1+
/**
2+
* https://leetcode.com/problems/longest-palindromic-substring/
3+
* time complexity : O(n)
4+
* space complexity : O(n^2)
5+
*/
6+
7+
function findPalindromeAroundCenter(s: string, leftIndex: number, rightIndex: number): [number, number] {
8+
while (leftIndex >= 0 && rightIndex < s.length && s[leftIndex] === s[rightIndex]) {
9+
leftIndex--; // 왼쪽으로 확장
10+
rightIndex++; // 오른쪽으로 확장
11+
}
12+
13+
// 팰린드롬의 시작과 끝 인덱스 반환
14+
return [leftIndex + 1, rightIndex - 1];
15+
}
16+
17+
function longestPalindrome(s: string): string {
18+
if (s.length <= 1) return s;
19+
20+
let longestPalindromeStartIndex = 0;
21+
let longestPalindromeLength = 0;
22+
23+
for (let centerIndex = 0; centerIndex < s.length; centerIndex++) {
24+
// 홀수 길이 팰린드롬 확인
25+
const [oddStart, oddEnd] = findPalindromeAroundCenter(s, centerIndex, centerIndex);
26+
const oddLength = oddEnd - oddStart + 1;
27+
28+
if (oddLength > longestPalindromeLength) {
29+
longestPalindromeStartIndex = oddStart;
30+
longestPalindromeLength = oddLength;
31+
}
32+
33+
// 짝수 길이 팰린드롬 확인
34+
const [evenStart, evenEnd] = findPalindromeAroundCenter(s, centerIndex, centerIndex + 1);
35+
const evenLength = evenEnd - evenStart + 1;
36+
37+
if (evenLength > longestPalindromeLength) {
38+
longestPalindromeStartIndex = evenStart;
39+
longestPalindromeLength = evenLength;
40+
}
41+
}
42+
43+
// 가장 긴 팰린드롬 부분 문자열 반환
44+
return s.substring(longestPalindromeStartIndex, longestPalindromeStartIndex + longestPalindromeLength);
45+
}

0 commit comments

Comments
 (0)