题解 | #密码截取#

密码截取

https://www.nowcoder.com/practice/3cd4621963e8454594f00199f4536bb1

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

// 寻找最长的回文串:暴力法
void async function () {
    const line = await readline();
    const len = line.length;
    let max = 0;
    for(let i = 0; i < len; i++){
        for(let j = 0; j <= len; j++){
            if(j-i<max || line.charAt(i) != line.charAt(j-1)) continue;
            const str = line.slice(i,j);
            if(str === str.split("").reverse().join("")) max = str.length;
        }
    }
    console.log(max);
}()

// 寻找最长的回文串:中心扩展算法
void (async function () {
    const line = await readline();
    const len = line.length;
    const expandAroundCenter = (i,j) =>{
        let left = i, right = j;
        while(left >= 0 && right < len && line.charAt(left) === line.charAt(right)) {
            left--;
            right++;
        }
        return right-left-1;
    } 
    let max = 0;
    for (let i = 0; i < len; i++) {
        max = Math.max(expandAroundCenter(i,i),expandAroundCenter(i,i+1),max);
    }
    console.log(max);
})();

全部评论

相关推荐

下北澤大天使:你是我见过最美的牛客女孩😍
点赞 评论 收藏
分享
评论
1
收藏
分享

创作者周榜

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