跳到正文

个人记录

DNA 序列(DNA)题解

sixwl约 1 分钟
原文
文章信息与版本

文章信息

收录
2025年12月12日
更新
2026年10月28日
篇幅
约 1 分钟

版本

  1. v1当前

思路: 哈希,用四进制数表示每个长度为k的子串,统计每个四进制数(即每个子串)的出现次数,找出最大出现次数

代码:

Python
#include<bits/stdc++.h>
using namespace std;
#define int long long

char s[5000010];
unordered_map<int,int> cnt;
int bd(char c){
	if(c=='A'){
		return 0;
	}
	if(c=='G'){
		return 1;
	}
	if(c=='C'){
		return 2;
	}
	return 3;
}
signed main() {
	freopen("DNA.in","r",stdin);
	freopen("DNA.out","w",stdout);
	int k;
	cin>>(s+1);
	cin>>k;
	int n=strlen(s+1);
	for(int i=1; i<=n; i++){
		int t=0;
		for(int j=i; j-i+1<=k; j++){
			t=t*4+bd(s[j]);
		}
		cnt[t]++;
	}
	int ans=0;
	for(auto x : cnt){
		ans=max(ans,x.second);
	}
	cout<<ans;
	return 0;
}
原文