当前位置:网站首页>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;
}
};
边栏推荐
- How to analyze the weekly activity rate?
- 【深度学习】今日bug(8月2)
- 【Unity入门计划】基本概念(8)-瓦片地图 TileMap 02
- JD6606SP5_JD6606SSP_JD6606SASP_JD6621W7百盛新纪元授权代理商
- 字典表(还需要输入2个字)
- [QT] Qt project demo: data is displayed on the ui interface, double-click the mouse to display specific information in a pop-up window
- DataGrip数据仓库工具
- 视频人脸识别和图片人脸识别的关系
- To add digital wings to education, NetEase Yunxin released the overall solution of "Internet + Education"
- 如何分析周活跃率?
猜你喜欢
瞌睡检测系统介绍
ffplay视频播放原理分析
带你了解什么是 Web3.0
[Deep Learning] Today's bug (August 2)
How to analyze the weekly activity rate?
TCP 可靠吗?为什么?
Interpretation of the 2021 Cost of Data Breach Report
To add digital wings to education, NetEase Yunxin released the overall solution of "Internet + Education"
Windows 事件转发到 SQL 数据库
Common distributed theories (CAP, BASE) and consensus protocols (Gosssip, Raft)
随机推荐
深入浅出Flask PIN
Interpretation of the 2021 Cost of Data Breach Report
ReentrantReadWriteLock详解
想进阿里?先来搞懂一下分布式事务
83. Remove Duplicates from Sorted List
Difference and performance comparison between HAL and LL library of STM32
Why do I strongly recommend using smart async?
【Unity入门计划】基本概念(8)-瓦片地图 TileMap 02
托尔斯泰:生活中只有两种不幸
MySQL窗口函数 OVER()函数介绍
#夏日挑战赛# HarmonyOS 实现一个绘画板
Common distributed theories (CAP, BASE) and consensus protocols (Gosssip, Raft)
使用Make/CMake编译ARM裸机程序(基于HT32F52352 Cortex-M0+)
Spark entry learning-2
vector类
QT QT 】 【 to have developed a good program for packaging into a dynamic library
window.open does not show favicon.icon
使用 PowerShell 将 Windows 转发事件导入 SQL Server
【QT】Qt 给已经开发好的程序快速封装成动态库
Windows 事件转发到 SQL 数据库