-
Notifications
You must be signed in to change notification settings - Fork 0
/
5. Longest Palindromic Substring.js
75 lines (62 loc) · 1.35 KB
/
5. Longest Palindromic Substring.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
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
/**
* @param {string} s
* @return {string}
*/
// dp解法
var longestPalindrome = function(s) {
var dp=[],len=s.length,maxlen=1,start=0;
for(var i=0;i<len;i++)
{
dp.push(new Array(len));
dp[i][i]=true;
}
for(var j=1;j<len;j++)
{
for( i=0;i<j;i++)
{
if(s.charAt(i) === s.charAt(j) &&(dp[i+1][j-1]||j-i===1))
{
dp[i][j]=true;
if(dp[i][j]&&(j-i+1 > maxlen))
{
maxlen=j-i+1;
start=i;
}
}
}
}
console.log(start);
return s.substr(start,maxlen);
};
/**
* @param {string} s
* @return {string}
*/
// 寻找中心点,向外寻找回文
var longestPalindrome = function(s) {
var len=s.length,maxlen=0,s1,s2,res;
for(var i=0;i<len;i++)
{
s1=checkPalindrome(s,i,i);
s2=checkPalindrome(s,i,i+1);
if(s1.length>maxlen)
{
maxlen=s1.length;
res=s1;
}
if(s2.length>maxlen)
{
maxlen=s2.length;
res=s2;
}
}
return res;
};
var checkPalindrome=function(s,low,high)
{
while(low>=0&&high<s.length&&s[low]===s[high])
{
low--;high++;
}
return s.substring(low+1,high);
};