This link has a great discussion on this problem. If you are refer to it. In fact, the "idea" and code in this passage are from the former link.
Well, there are a very intuitive solution to this problem. That's, starting from the first letter of the string, extract a substring of length , check whether it has OCC Urred and not been added to the result. If So, add it to the result; Otherwise, visit the next letter and repeat the above process. However, a naive implementation of this idea would give the MLE error, and this is the real obstacle of the proble M.
Then we need to save spaces. Instead of keeping the whole substring, can is convert it to other formats? Well, you had noticed that there is only 4 letters A, T, C, G in the substring. If we assign each letter 2 bits, then a -letter substring would only cost $ bits and can thus Be accommodated by a -bit integer, greatly lowering the space complexity.
Then you could put this idea into code and get a simple Accepted solution as follows. congratulations!
1 classSolution {2 Public:3vector<string> findrepeateddnasequences (strings) {4unordered_map<int,int>MP;5vector<string>Res;6 inti =0, code =0;7 while(I <9)8Code = ((Code <<2) | Mapping (s[i++]));9 for(; I < (int) s.length (); i++) {TenCode = ((Code <<2) &0xfffff) |mapping (S[i])); One if(mp[code]++ = =1) ARes.push_back (S.substr (i-9,Ten)); - } - returnRes; the } - Private: - intMappingChars) { - if(s = ='A')return 0; + if(s = ='C')return 1; - if(s = ='G')return 2; + if(s = ='T')return 3; A } at};
Do you see the logic in the above code? Well, we first Merge 9 letters into code . Then, each time we meet a new letter, we merge it to code by & 0xfffff (5 hexadecimal digits). Thus we have a code for the current 10 - Letter substring. We Check whether it has occurred exactly for once to decide whether to push it to the result or not.
The above code can still is shorten using tricks from the above link. In fact, if we code A, T, C, G using 3 bits, the code would be as short as ten lines! Refer to the above link to learn more!
[Leetcode] Repeated DNA sequences