题解 | #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 }