题解 | 最长回文子串

最长回文子串

https://www.nowcoder.com/practice/12e081cd10ee4794a2bd70c7d68f5507

const readline = require('readline');

const rl = readline.createInterface({
    input: process.stdin,
    output: process.stdout
});

function expendAroundCenter(s, left, right) {
    while(left >= 0 && right < s.length && s[left] === s[right]) {
        left--;
        right++;
    }
    return right - left - 1;
}

function longestPalindrome(str) {
    if (!str.length) return '';
    let start = 0;
    let end = 0;
    for(let i = 0; i < str.length; i++) {
        const len1 = expendAroundCenter(str, i, i);
        const len2 = expendAroundCenter(str, i, i+1);
        const len = Math.max(len1, len2);
        if (len > end - start) {
            start = i - Math.floor((len - 1) / 2);
            end = i + Math.floor(len / 2);
        }
    }
    return str.substring(start, end + 1);
}


rl.on('line', function (line) {
    const result = longestPalindrome(line);
    console.log(result.length);
});

全部评论

相关推荐

评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务