Skip to content

Commit c39ca6d

Browse files
committed
Add longest-palindromic-substring solution
1 parent 4763cfc commit c39ca6d

File tree

1 file changed

+76
-0
lines changed

1 file changed

+76
-0
lines changed
+76
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,76 @@
1+
// ✅ Time Complexity: O(n^2), where n represents the length of the input string s
2+
// ✅ Space Complexity: O(n)
3+
4+
/**
5+
* @param {string} s
6+
* @return {string}
7+
*/
8+
var longestPalindrome = function (s) {
9+
let max_left = 0,
10+
max_right = 0;
11+
12+
for (let i = 0; i < s.length; i++) {
13+
// Odd-length palindromes
14+
let left = i,
15+
right = i;
16+
17+
while (left >= 0 && right < s.length && s[left] === s[right]) {
18+
if (max_right - max_left < right - left) {
19+
max_right = right;
20+
max_left = left;
21+
}
22+
left -= 1;
23+
right += 1;
24+
}
25+
26+
// Even-length palindromes
27+
left = i;
28+
right = i + 1;
29+
30+
while (left >= 0 && right < s.length && s[left] === s[right]) {
31+
if (max_right - max_left < right - left) {
32+
max_right = right;
33+
max_left = left;
34+
}
35+
left -= 1;
36+
right += 1;
37+
}
38+
}
39+
40+
return s.slice(max_left, max_right + 1);
41+
};
42+
43+
// ✅ Time Complexity: O(n^3), where n represents the length of the input string s
44+
// ✅ Space Complexity: O(n)
45+
46+
/**
47+
* @param {string} s
48+
* @return {string}
49+
*/
50+
// var longestPalindrome = function (s) {
51+
// const isPalindromic = (left, right) => {
52+
// while (left < right) {
53+
// if (s[left] !== s[right]) {
54+
// return false;
55+
// }
56+
// left += 1;
57+
// right -= 1;
58+
// }
59+
60+
// return true;
61+
// };
62+
63+
// let max_left = 0,
64+
// max_right = 0;
65+
// for (let l = 0; l < s.length; l++) {
66+
// for (let r = 0; r < s.length; r++) {
67+
// if (isPalindromic(l, r) && max_right - max_left < r - l) {
68+
// max_left = l;
69+
// max_right = r;
70+
// }
71+
// }
72+
// }
73+
74+
// return s.slice(max_left, max_right + 1);
75+
// };
76+

0 commit comments

Comments
 (0)