题解 | DNA序列
DNA序列
https://www.nowcoder.com/practice/e8480ed7501640709354db1cc4ffd42a
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 const str = await readline(); const length = await readline(); let strArr = []; getAllSubstring(str); //找到该字符串的所有字串 function getAllSubstring(str) { for (let i = 0; i < str.length; i++) { for (let j = i + 1; j <= str.length; j++) { strArr.push(str.slice(i, j)); } } } //找出符合题目给出的字符子串长度并且含”G“和”C“的最多的字串 let res = strArr .filter((item) => item.length == length) .reduce((maxItem, currentItem) => { //accumulator(累积器,maxItem):到当前迭代为止的归约结果,即目前找到的包含'G'和'C'最多的子字符串。第一次迭代时候默认为数组的第一项 //currentValue(当前值,currentItem):数组中当前正在处理的元素。 let maxGCCount = (maxItem.match(/G/g) || []).length + (maxItem.match(/C/g) || []).length; let currentGCCount = (currentItem.match(/G/g) || []).length + (currentItem.match(/C/g) || []).length; // 如果当前项含"G"和"C"的总数大于当前最大值,则返回当前项作为新的最大值 return currentGCCount > maxGCCount ? currentItem : maxItem; }, ""); console.log(res) })();