题解 | #最长回文子串#

最长回文子串

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

const rl = require("readline").createInterface({ input: process.stdin });
var iter = rl[Symbol.asyncIterator]();
const readline = async () => (await iter.next()).value;

void (async function () {
    // Write your code here
    while ((line = await readline())) {
        let res = 0;
        for (let i = 1; i < line.length; i++) {
            let cur = line[i];
            let pre = line[i - 1];
            let next = line[i + 1];
            let left, right;
            let max = 1;
             if(cur === pre) {
                // 奇数
                left = i - 1;
                right = i;
                max = max + 1;
            }else if (next === pre) {
                // 偶数
                left = i - 1;
                right = i + 1;
                max = max + 2;
            } 

            while (left > 0 && right < line.length - 1 && max > 1) {
                left--;
                right++;
                if (line[left] === line[right]) {
                    max = max + 2;
                    // console.log(left, right, max);
                } else {
                    res = Math.max(res, max);
                    break;
                }
            }
            res = Math.max(res, max);
        }
        console.log(res);
    }
})();

全部评论

相关推荐

不放弃的小鱼干很洒脱:好可爱的离职理由
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客企业服务