forked from codedecks-in/LeetCode-Solutions
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path5.Longest-Palindromic-Substring.js
More file actions
54 lines (46 loc) · 879 Bytes
/
5.Longest-Palindromic-Substring.js
File metadata and controls
54 lines (46 loc) · 879 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
/**
* Given a string s, return the longest palindromic substring in s.
*
* Example 1:
Input: s = "babad"
Output: "bab"
Note: "aba" is also a valid answer.
Example 2:
Input: s = "cbbd"
Output: "bb"
Example 3:
Input: s = "a"
Output: "a"
Example 4:
Input: s = "ac"
Output: "a"
Constraints:
1 <= s.length <= 1000
s consist of only digits and English letters (lower-case and/or upper-case),
*/
/**
* @param {string} s
* @return {string}
*/
var longestPalindrome = function (s) {
var max = 0;
var head = 0;
var n = s.length;
var i = 0;
while (i < n - max / 2) {
var lo = i;
while (i < n && s[i] === s[lo]) {
i++;
}
var hi = i - 1;
while (lo >= 0 && hi < n && s[lo] === s[hi]) {
lo--;
hi++;
}
if (hi - lo - 1 > max) {
max = hi - lo - 1;
head = lo + 1;
}
}
return s.slice(head, head + max);
};