当前位置:网站首页>leetcode:187. 重复的DNA序列
leetcode:187. 重复的DNA序列
2022-08-03 16:05:00 【OceanStar的学习笔记】
题目来源
题目描述

class Solution {
public:
vector<string> findRepeatedDnaSequences(string s) {
}
};
题目解析
哈希表
我们可以用一个哈希表统计 ss 所有长度为 1010 的子串的出现次数,返回所有出现次数超过 1010 的子串。
代码实现时,可以一边遍历子串一边记录答案,为了不重复记录答案,我们只统计当前出现次数为 22 的子串。
class Solution {
const int L = 10;
public:
vector<string> findRepeatedDnaSequences(string s) {
vector<string> ans;
unordered_map<string, int> cnt;
int n = s.length();
for (int i = 0; i <= n - L; ++i) {
string sub = s.substr(i, L);
if (++cnt[sub] == 2) {
ans.push_back(sub);
}
}
return ans;
}
};

一定要用unordered_map,CPP的unordered_map就不需要再将字符串转hash值了
前缀树优化
class Solution {
struct Trie{
int cnt;
std::vector<Trie *> vec;
Trie(){
cnt = 0;
vec.resize(26);
}
};
bool buildTrie(std::string &s, int start, Trie * root){
Trie *node = root;
for (int i = start; i < start + 10; ++i) {
int c = s[i] - 'A';
if(node->vec[c] == nullptr){
node->vec[c] = new Trie();
}
node = node->vec[c];
}
bool flag = false;
node->cnt++;
if(node->cnt == 2){
flag = true;
}
return flag;
}
public:
vector<string> findRepeatedDnaSequences(string s) {
int N = s.size();
vector<string> ans;
Trie *root = new Trie();
for (int i = 0; i < N - 9; ++i) {
if(buildTrie(s, i, root)){
ans.push_back(s.substr(i, 10));
}
}
return ans;
}
};
边栏推荐
猜你喜欢

"Avnet Embedded Weekly" Issue 276: 2022.07.25--2022.07.31

To participate in sweepstakes, incoming new programmers magazine welfare!

DataGrip:非常好用的数据库工具,安装与使用教程,亮点介绍

2021年数据泄露成本报告解读

甲方不让用开源【监控软件】?大不了我自己写一个

MPLS的wpn实验

为什么我强烈推荐使用智能化async?

QT QT 】 【 to have developed a good program for packaging into a dynamic library

Spark entry learning-2

Yuan xiaolin: Volvo focus on travel security, and put it perfectly
随机推荐
从零开始搭建MySQL主从复制架构
扩展欧几里得求逆元实例
ModelWhale 云端运行 WRF 中尺度数值气象模式,随时随地即开即用的一体化工作流
Analysis of ffplay video playback principle
【Unity入门计划】基本概念(8)-瓦片地图 TileMap 02
AI+BI+可视化,Sugar BI架构深度剖析
如何分析周活跃率?
罗克韦尔AB PLC RSLogix5000中创建新项目、任务、程序和例程的具体方法和步骤
2021年数据泄露成本报告解读
5 v 8.4 v1A charging current charging management IC
一文看懂推荐系统:召回03:基于用户的协同过滤(UserCF),要计算用户之间的相似度
TCP 可靠吗?为什么?
Detailed ReentrantLock
30W 2C(JD6606S + FP6652X2)BOM
泰山OFFICE技术讲座:文字边框高度研究
如何选择合适的损失函数,请看......
DataGrip数据仓库工具
MySQL窗口函数 PARTITION BY()函数介绍
uniapp隐藏导航栏和横屏显示设置
Windows 事件查看器记录到 MYSQL