Skip to content

Commit c692b30

Browse files
ongzxChi Hi Ong
andauthored
Add Leetcode #5 solution (#66)
Co-authored-by: Chi Hi Ong <[email protected]>
1 parent 8747cb9 commit c692b30

File tree

2 files changed

+56
-0
lines changed

2 files changed

+56
-0
lines changed
Lines changed: 54 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,54 @@
1+
/**
2+
* Given a string s, return the longest palindromic substring in s.
3+
*
4+
* Example 1:
5+
6+
Input: s = "babad"
7+
Output: "bab"
8+
Note: "aba" is also a valid answer.
9+
Example 2:
10+
11+
Input: s = "cbbd"
12+
Output: "bb"
13+
Example 3:
14+
15+
Input: s = "a"
16+
Output: "a"
17+
Example 4:
18+
19+
Input: s = "ac"
20+
Output: "a"
21+
22+
23+
Constraints:
24+
25+
1 <= s.length <= 1000
26+
s consist of only digits and English letters (lower-case and/or upper-case),
27+
*/
28+
29+
/**
30+
* @param {string} s
31+
* @return {string}
32+
*/
33+
var longestPalindrome = function (s) {
34+
var max = 0;
35+
var head = 0;
36+
var n = s.length;
37+
var i = 0;
38+
while (i < n - max / 2) {
39+
var lo = i;
40+
while (i < n && s[i] === s[lo]) {
41+
i++;
42+
}
43+
var hi = i - 1;
44+
while (lo >= 0 && hi < n && s[lo] === s[hi]) {
45+
lo--;
46+
hi++;
47+
}
48+
if (hi - lo - 1 > max) {
49+
max = hi - lo - 1;
50+
head = lo + 1;
51+
}
52+
}
53+
return s.slice(head, head + max);
54+
};

README.md

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -220,6 +220,8 @@ Check out ---> [Sample PR](https://github.com/codedecks-in/LeetCode-Solutions/pu
220220
| --- | --------------------------------------------------------------------------------------------- | --------------------------------------------------- | -------- | ------ | ---------- | --- | ---------------- |
221221
| 005 | [Longest Palindromic Substring](https://leetcode.com/problems/longest-palindromic-substring/) | [Python](./Python/5_LongestPalindromicSubstring.py) | _O(N^2)_ | _O(N)_ | Medium | | Expand the Wings |
222222
| 4 | [Median of Two Sorted Arrays](https://leetcode.com/problems/median-of-two-sorted-arrays/) | [Java](./Java/median-of-two-sorted-arrays.java) | _O(log(min(m,n)))_ | _O(1)_ | Hard | | |
223+
| 005 | [Longest Palindromic Substring](https://leetcode.com/problems/longest-palindromic-substring/) | [JavaScript](./JavaScript/5.Longest-Palindromic-Substring.js) | _O(N^2)_ | _O(1)_ | Medium | | |
224+
223225
<br/>
224226
<div align="right">
225227
<b><a href="#algorithms">⬆️ Back to Top</a></b>

0 commit comments

Comments
 (0)