LeetCode187—Repeated DNA Sequences

比眉伴天荒 2022-07-13 02:43 279阅读 0赞

原题

原题链接

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.

For example,

Given s = “AAAAACCCCCAAAAACCCCCCAAAAAGGGTTT”,

Return:
[“AAAAACCCCC”, “CCCCCAAAAA”].


分析

重复出现的子串,长度为10。
用一个hash来保存,最后结果去重即可。

  1. class Solution{
  2. public:
  3. vector<string> findRepeatedDnaSequences(string s)
  4. {
  5. vector<string>result;
  6. unordered_set<string>visited;
  7. for(int i=0;i+10<=s.size();++i)
  8. {
  9. string tmp(s.begin()+i,s.begin()+i+10);
  10. if(visited.end()==visited.find(tmp))
  11. {
  12. visited.insert(tmp);
  13. }
  14. else
  15. result.push_back(tmp);
  16. }
  17. //去重
  18. result.erase(unique(result.begin(),result.end()),result.end());
  19. //打印
  20. // ostream_iterator<string> out_it(cout,"\n");
  21. // copy(result.begin(),result.end(),out_it);
  22. return result;
  23. }
  24. };

发表评论

表情:
评论列表 (有 0 条评论,279人围观)

还没有评论,来说两句吧...

相关阅读