-
-
Notifications
You must be signed in to change notification settings - Fork 235
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
最长回文子串 #312
Comments
题目链接:https://leetcode.cn/problems/longest-palindromic-substring/description /**
* @param {string} s
* @return {number}
*/
var longestPalindrome = function(s) {
let ans='';
let n=s.length;
let f=new Array(n).fill(0).map(() => new Array(n).fill(0));
for(let i=0;i<n;i++) f[i][i]=1;
for(let len=2;len<=n;len++)
{
for(let i=0;i+len-1<n;i++)
{
let j=i+len-1;
if(s[i]===s[j]&&f[i+1][j-1]+2===j-i+1) {
f[i][j]=f[i+1][j-1]+2;
}
}
}
let l=n,r=0;
for(let i=0;i<n;i++)
{
for(let j=0;j<n;j++)
{
if(f[i][j]===j-i+1)
{
if(j-i>r-l)
{
l=i,r=j;
}
}
}
}
return s.substring(l,r+1);
}; |
/**
* @param {string} s
* @return {string}
*/
var longestPalindrome = function(s) {
let max = ''
for(let i = 0; i < s.length; i++){
helper(i,i)
helper(i,i + 1)
}
function helper(left, right){
while(left >= 0 && right < s.length && s[left] === s[right]){
left--
right++
}
const maxStr = s.slice(left + 1, right - 1 + 1) //这里+1-1只是为了便于理解
if(maxStr.length > max.length){
max = maxStr
}
}
return max
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
No description provided.
The text was updated successfully, but these errors were encountered: