Skip to content

Commit d3c1f99

Browse files
Jeehay28Jeehay28
authored andcommitted
Add longest-palindromic-substring solution in TS
1 parent 61995ee commit d3c1f99

File tree

1 file changed

+26
-0
lines changed

1 file changed

+26
-0
lines changed
Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,26 @@
1+
// TC: O(n^2)
2+
// SC: O(1)
3+
function longestPalindrome(s: string): string {
4+
if (s.length < 2) return s;
5+
6+
let maxLeft = 0;
7+
let maxRight = 0;
8+
9+
const expandWindow = (left: number, right: number): void => {
10+
while (left >= 0 && right < s.length && s[left] === s[right]) {
11+
if (maxRight - maxLeft < right - left) {
12+
maxRight = right;
13+
maxLeft = left;
14+
}
15+
left--;
16+
right++;
17+
}
18+
};
19+
20+
for (let i = 0; i < s.length; i++) {
21+
expandWindow(i, i); // odd length palindrome
22+
expandWindow(i, i + 1); // even length palindrome
23+
}
24+
25+
return s.slice(maxLeft, maxRight + 1);
26+
}

0 commit comments

Comments
 (0)