Share my c++ solution


  • 0
    V
    class Solution {
    public:
        vector<string> findRepeatedDnaSequences(string s) {
            int i = 0, n = s.size(), code = 0;
            string temp;
            vector<string> ret;
            unordered_map<int, int> m;
            
            if (n < 11)
                return ret;
                
            n -= 10;
            for (i = 0; i <= n; ++i)
            {
                temp = s.substr(i, 10);
                code = myEncode(temp);
                
                if (m.find(code) != m.end())
                {
                    if (m[code] == 1)
                    {
                        ret.push_back(temp);
                        ++m[code];
                    }
                }
                else
                    m[code] = 1;
            }
            
            return ret;
        }
        
        int myEncode(string ss)
        {
            int i = 0, code = 0;
            
            for (i = 0; i < 10; ++i)
            {
                code = code << 2;
                switch (ss[i])
                {
                    case 'A':
                        code += 0;
                        break;
                    case 'C':
                        code += 1;
                        break;
                    case 'G':
                        code += 2;
                        break;
                    case 'T':
                        code += 3;
                        break;
                }
            }
            
            return code;
        }
    };

Log in to reply
 

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