Skip to content

Commit 90424df

Browse files
committed
Added longestPalindromic solution
1 parent 93c716d commit 90424df

File tree

1 file changed

+32
-0
lines changed

1 file changed

+32
-0
lines changed
+32
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,32 @@
1+
var longestPalindrome = function (s) {
2+
let maxStart = 0,
3+
maxEnd = 0;
4+
5+
for (let i = 0; i < s.length; i++) {
6+
let start = i,
7+
end = i;
8+
while (start >= 0 && end < s.length && s[start] === s[end]) {
9+
if (end - start > maxEnd - maxStart) {
10+
maxStart = start;
11+
maxEnd = end;
12+
}
13+
start--;
14+
end++;
15+
}
16+
17+
(start = i), (end = i + 1);
18+
while (start >= 0 && end < s.length && s[start] === s[end]) {
19+
if (end - start > maxEnd - maxStart) {
20+
maxStart = start;
21+
maxEnd = end;
22+
}
23+
start--;
24+
end++;
25+
}
26+
}
27+
28+
return s.slice(maxStart, maxEnd + 1);
29+
};
30+
31+
// TC: O(n^2)
32+
// SC: O(1)

0 commit comments

Comments
 (0)