题解 | #DNA序列#

DNA序列

https://www.nowcoder.com/practice/e8480ed7501640709354db1cc4ffd42a

const readline = require('readline');

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

// 定义保存DNA序列和子串长度的变量
let [dna, len, num] = [undefined, undefined, 0]

rl.on('line', function (line) {
    num++
    if(num === 1){
        // 保存dna字符串序列
        dna = line
    }else if(num === 2){
        // 隐式将字符串转成数字
        len = line * 1
        const childStrArr = []
        // 找出dna序列中所有长度为len的连续子串,字符不连续的的不能算字符串
        // DNA序列为 ACGT 的子串有: ACG , CG , CGT 等等,但是没有 AGT , CT 等等
        for(let i = 0; i <= dna.length-len; i++){
            childStrArr.push(dna.slice(i,i+len))
        }

        // 遍历找出CG比例最高的字符串
        let [max, targetStr] = [0, '']
        for(let i = 0; i < childStrArr.length; i++){
            const tmpCount = countCgRatio(childStrArr[i])
            if(tmpCount > max){
                max = tmpCount
                targetStr = childStrArr[i]
            }
        }
        // 输出最长字串
        console.log(targetStr)
    }
});


function countCgRatio(str: string){
    let count = 0
    for(let i = 0; i < str.length; i++){
        if(['C','G'].includes(str[i])){
            count++
        }
    }

    return count / str.length
}

全部评论

相关推荐

程序员小白条:你是沟通了900个,不是投了900份简历,你能投900份,意味着对面都要回复你900次,你早就找到实习了,没亮点就是这样的,别局限地区,时间投的也要早,现在都要7月了
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

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