LeetCode刷题实战187:重复的DNA序列
All DNA is composed of a series of nucleotides abbreviated as 'A', 'C', 'G', and 'T', for example: "ACGAATTCCG". When studying DNA, it is sometimes useful to identify repeated sequences within the DNA.
Write a function to find all the 10-letter-long sequences (substrings) that occur more than once in a DNA molecule.
题意
示例
示例 1:
输入:s = "AAAAACCCCCAAAAACCCCCCAAAAAGGGTTT"
输出:["AAAAACCCCC","CCCCCAAAAA"]
示例 2:
输入:s = "AAAAAAAAAAAAA"
输出:["AAAAAAAAAA"]
提示:
0 <= s.length <= 105
s[i] 为 'A'、'C'、'G' 或 'T'
解题
class Solution {
public:
vector<string> findRepeatedDnaSequences(string s) {
vector<string> result;
unordered_map<string, int> myMap;//用于关联各个长度为10的子串出现的次数
int strSize = s.size();
for (int beginIndex = 0; beginIndex <= strSize - 10; ++beginIndex) {
string tempRes = s.substr(beginIndex, 10);
if (++myMap[tempRes] == 2) {//第一次出现两次,避免重复
result.push_back(tempRes);
}
}
return result;
}
};