Skip to content

Commit 606da9c

Browse files
committed
Feat: 5. Longest Palindromic Substring
1 parent e16fd48 commit 606da9c

File tree

1 file changed

+32
-0
lines changed

1 file changed

+32
-0
lines changed
Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,32 @@
1+
/**
2+
* https://leetcode.com/problems/longest-palindromic-substring
3+
* T.C. O(n^2)
4+
* S.C. O(1)
5+
*/
6+
function longestPalindrome(s: string): string {
7+
if (s.length < 2) return s;
8+
let start = 0;
9+
let end = 0;
10+
11+
for (let i = 0; i < s.length; i++) {
12+
const len1 = expandBothSides(s, i, i); // odd
13+
const len2 = expandBothSides(s, i, i + 1); // even
14+
const len = Math.max(len1, len2);
15+
16+
if (len > end - start) {
17+
start = i - Math.floor((len - 1) / 2);
18+
end = i + Math.floor(len / 2);
19+
}
20+
}
21+
22+
return s.slice(start, end + 1);
23+
}
24+
25+
function expandBothSides(s: string, left: number, right: number): number {
26+
while (0 <= left && right < s.length && s[left] === s[right]) {
27+
left--;
28+
right++;
29+
}
30+
31+
return right - left - 1;
32+
}

0 commit comments

Comments
 (0)