Simple C++ solution, a little bit slow


  • 0
    C
    int hash_func(string s)
    {
        int len = s.length();
        int ans = 0;
        int seed = 13131;
        for(int i = 0; i < len; ++i)
        {
            ans = ans*seed + s[i];
        }
        return ans;
        
    }
    vector<string> findRepeatedDnaSequences(string s) {
        
        vector<string> ans;
        unordered_map<int,int> ans_mp;
        int len = s.length();
        if(len<11)return ans;
        for(int i = 0; i < len; ++i)
        {
            if(i+10>len)break;
            string sub_s = s.substr(i,10);
            int hash_res = hash_func(sub_s);
            if(ans_mp.find(hash_res)==ans_mp.end())
            {
                ans_mp[hash_res] = 1;
            }
            else
            {
                if(ans_mp[hash_res]==1)
                {
                    ans.push_back(sub_s);
                    ans_mp[hash_res]++;
                }
            }
        }
        return ans;
        
    }

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.