题解 | #在字符串中找出连续最长的数字串#

在字符串中找出连续最长的数字串

https://www.nowcoder.com/practice/2c81f88ecd5a4cc395b5308a99afbbec

// 输入:
//  abcd12345ed125ss123058789
//  a8a72a6a5yy98y65ee1r2
// 输出:
//  123058789,9
//  729865,2
// 说明:
//  样例一最长的数字子串为123058789,长度为9
//  样例二最长的数字子串有72,98,65,长度都为2 
const rl = require("readline").createInterface({ input: process.stdin });
var iter = rl[Symbol.asyncIterator]();
const readline = async () => (await iter.next()).value;

const matchDecimal = (str) => str.match(/\d/);
function findLongestSubstr(str) {
    let substrMap = {};
    for (let i = 0; i < str.length - 2; i++) {
        const char = str[i];
        const match = matchDecimal(char);
        if (!match) {
            continue;
        }
        let j = i + 1;
        for (; j < str.length; j++) {
            if (!matchDecimal(str[j])) {
                break;
            }
        }
        const substr = str.substring(i, j);
        const substrLen = substr.length;
        let substrArr = substrMap[substrLen];
        if (substrArr) {
            substrArr.push(substr);
        } else {
            substrMap[substrLen] = [substr];
        }
    }
    let maxLength = Math.max(...Object.keys(substrMap).map(Number));
    let longestSubstr = "";
    substrMap[maxLength].forEach((substr) => {
        longestSubstr += substr;
    });
    console.log(`${longestSubstr},${maxLength}`);
}

void (async function () {
    // Write your code here
    while ((line = await readline())) {
        findLongestSubstr(line);
    }
})();

#华为OD题库##华为OD机试算法题库##小白算法成长之路##前端刷算法#
全部评论

相关推荐

牛客482196251号:你是我见过最大的牛客女孩,这个评论是我给你的礼物
点赞 评论 收藏
分享
我也曾抱有希望:说的好直白
点赞 评论 收藏
分享
点赞 收藏 评论
分享
牛客网
牛客企业服务