-
Notifications
You must be signed in to change notification settings - Fork 70
/
res.js
44 lines (39 loc) · 931 Bytes
/
res.js
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
/**
* res.js
* @authors Joe Jiang ([email protected])
* @date 2017-05-10 17:35:02
*
* @param {string} s
* @return {string}
*/
let longestPalindrome = function(s) {
let len = s.length,
end = len-1,
sarray = s.split('');
if(len<2) {
return s;
}
let resfrom = 0,
resto = 0;
for(let i=0; i<end; i++) {
expandPalindrome(i,i);
if (sarray[i] === sarray[i+1]) {
expandPalindrome(i,i+1);
}
}
return s.substring(resfrom, resto+1);
function expandPalindrome(start, stop) {
while (start>0 && stop<end) {
if (sarray[start-1] === sarray[stop+1]) {
start--;
stop++;
} else {
break;
}
}
if (stop-start>resto-resfrom) {
resfrom = start;
resto = stop;
}
}
};