Skip to content

Commit 7172ab9

Browse files
committed
Add week 10 solutions: longestPalindromicSubstring
1 parent 42c41cd commit 7172ab9

File tree

1 file changed

+31
-0
lines changed

1 file changed

+31
-0
lines changed
+31
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,31 @@
1+
// Time Complexity: O(n^2)
2+
// Space Complexity: O(1)
3+
4+
var longestPalindrome = function (s) {
5+
let start = 0,
6+
maxLength = 1;
7+
8+
// to expand around the center and update the start and maxLength
9+
function expandAroundCenter(left, right) {
10+
while (left >= 0 && right < s.length && s[left] === s[right]) {
11+
left--;
12+
right++;
13+
}
14+
// update the start and maxLength if a longer palindrome is found
15+
if (maxLength < right - left - 1) {
16+
start = left + 1;
17+
maxLength = right - left - 1;
18+
}
19+
}
20+
21+
// iterate through each character in the string
22+
for (let i = 0; i < s.length; i++) {
23+
// expand around the current character
24+
expandAroundCenter(i, i);
25+
// expand around the current and next character
26+
expandAroundCenter(i, i + 1);
27+
}
28+
29+
// return the longest palindromic substring
30+
return s.substring(start, start + maxLength);
31+
};

0 commit comments

Comments
 (0)