问题描述
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.
Example:
Input: s = “AAAAACCCCCAAAAACCCCCCAAAAAGGGTTT”
Output: [“AAAAACCCCC”, “CCCCCAAAAA”]
思路分析
给一个string代表DNA序列,找到窗口长度为10的在s中国出现超过1次的子串。
利用map来在循环中统计每一个子串出现的次数,然后遍历map,将出现次数大于1的存入res中。
代码
class Solution {
public:
vector<string> findRepeatedDnaSequences(string s) {
vector<string> res;
if (s.length() <= 10)
return res;
unordered_map<string, int> map;
for (int i = 0; i <= s.length() - 10; i++){
string temp = s.substr(i, 10);
map[temp]++;
}
for (auto it = map.begin(); it != map.end(); it++){
if (it->second > 1)
res.push_back(it->first);
}
return res;
}
};
时间复杂度:
O(n2)
空间复杂度:
O(n)
反思
看到python的解法感觉很是简洁。利用collection库计数,利用列表解析式生成结果。果然是要玩转这些第三方库才能横着走啊。