Skip to content
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

Open
Sunny-117 opened this issue Nov 8, 2022 · 2 comments
Open

最长回文子串 #312

Sunny-117 opened this issue Nov 8, 2022 · 2 comments

Comments

@Sunny-117
Copy link
Owner

No description provided.

@Pcjmy
Copy link
Contributor

Pcjmy commented Jan 19, 2023

题目链接:https://leetcode.cn/problems/longest-palindromic-substring/description
时间复杂度:O(n^2)

/**
 * @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);
};

@lxy-Jason
Copy link
Contributor

/**
 * @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
Labels
None yet
Projects
None yet
Development

No branches or pull requests

3 participants