题解 | #DNA序列#
DNA序列
https://www.nowcoder.com/practice/e8480ed7501640709354db1cc4ffd42a
思路:滑动窗口加哈希表加排序,窗口长度为子串长度,用字典记录每个
窗口G和C出现的次数,然后转化为列表按次数降序、左索引升序排序,
assist[0][0]就是GC最多的第一个出现的子串左索引
from collections import defaultdict def gc_ratio(): dna = input() n = int(input()) l = len(dna) left = 0 count = defaultdict(lambda:0) while left<l-n+1: for i in range(left,left+n): if dna[i]=='C' or dna[i]=='G': count[left]+=1 if count[left]==n: print(dna[left:left+n]) return left+=1 assist = list(count.items()) assist.sort(key=lambda x:(-x[1],x[0])) print(dna[assist[0][0]:assist[0][0]+n]) gc_ratio()