题目

类型:HashTable

image.png

解题思路

image.png

代码

  1. public class RepeatedDNASequences {
  2. int N = (int)1e5+10, P = 131313;
  3. int[] h = new int[N], p = new int[N];
  4. public List<String> findRepeatedDnaSequences(String s) {
  5. int n = s.length();
  6. List<String> ans = new ArrayList<>();
  7. p[0] = 1;
  8. for (int i = 1; i <= n; i++) {
  9. h[i] = h[i - 1] * P + s.charAt(i - 1);
  10. p[i] = p[i - 1] * P;
  11. }
  12. Map<Integer, Integer> map = new HashMap<>();
  13. for (int i = 1; i + 10 - 1 <= n; i++) {
  14. int j = i + 10 - 1;
  15. int hash = h[j] - h[i - 1] * p[j - i + 1];
  16. int cnt = map.getOrDefault(hash, 0);
  17. if (cnt == 1) ans.add(s.substring(i - 1, i + 10 - 1));
  18. map.put(hash, cnt + 1);
  19. }
  20. return ans;
  21. }
  22. }