算法/leetcode刷题记录/字符串

5.最长回文子串
要点在于分情况统计

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
var longestPalindrome = function(s) {
if(s.length<=1){
return s
}
let maxPostiton, maxLength = 0
for(let i = 0; i<s.length;i++){
const l1 = help1(s, i)
const l2 = help2(s, i)
if(l1>maxLength){
maxLength = l1
maxPostiton = i
}
if(l2>maxLength){
maxLength = l2
maxPostiton = i
}
}
// 长度为奇数的情况
function help1(s, pos){
let length = 0
for(let i = 0;pos+i<s.length && pos -i >=0;i++){
if(s[pos+i] === s[pos-i]){
length = 2*i + 1
}else{
break
}

}
return length
}
// 长度为偶数的情况
function help2(s, pos){
let length = 0
for(let i = 0;pos+i+1<s.length && pos-i>=0;i++){
if(s[pos+1+i] === s[pos-i]){
length = 2*(i+1)
}else{
break
}

}
return length
}
return s.substr( maxPostiton - (Math.ceil(maxLength/2)-1), maxLength)
};