leetcode:187. 重复的DNA序列

题目来源

题目描述

在这里插入图片描述

class Solution {
public:
    vector<string> findRepeatedDnaSequences(string s) {

    }
};

题目解析

哈希表

我们可以用一个哈希表统计 ss 所有长度为 1010 的子串的出现次数,返回所有出现次数超过 10 的子串。

代码实现时,可以一边遍历子串一边记录答案,为了不重复记录答案,我们只统计当前出现次数为 2 的子串。

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;
    }
};
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值