1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28
| class Solution { static int length = 10; Map<Character, Integer> map = new HashMap<>() {{ put('A', 0); put('C', 1); put('G', 2); put('T', 3); }};
public List<String> findRepeatedDnaSequences(String s) { List<String> ans = new ArrayList<>(); int n = s.length(); if (n <= length) return ans; int x = 0; for (int i = 0; i < length - 1; ++i) { x = (x << 2) | map.get(s.charAt(i)); } Map<Integer, Integer> cnt = new HashMap<>(); for (int i = 0; i + length <= n; ++i) { x = ((x << 2) | map.get(s.charAt(i + length - 1))) & ((1 << (length * 2)) - 1); cnt.put(x, cnt.getOrDefault(x, 0) + 1); if (cnt.get(x) == 2) { ans.add(s.substring(i, i + length)); } } return ans; } }
|