题意:

image.png

解题思路:

  1. 1. 滑动窗口+哈希表O(n)
  2. 2. 0 开始每次截取字符串10个长度放入哈希表中;
  3. 3. 从前往后扫描,出现重复串,将其哈希值++;
  4. 4. 最后统计大于1的哈希值;

PHP代码实现:

  1. class Solution {
  2. /**
  3. * @param String $s
  4. * @return String[]
  5. */
  6. function findRepeatedDnaSequences($s) {
  7. $map = [];
  8. for ($i = 0; $i + 10 <= strlen($s); $i++) {
  9. $map[substr($s, $i, 10)]++;
  10. }
  11. $res = [];
  12. foreach ($map as $k => $v) {
  13. if ($v > 1) array_push($res, $k);
  14. }
  15. return $res;
  16. }
  17. }

go代码实现:

  1. func findRepeatedDnaSequences(s string) []string {
  2. mp := make(map[string]int)
  3. for i := 0; i + 10 <= len(s); i++ {
  4. mp[s[i:i+10]]++
  5. }
  6. res := make([]string, 0)
  7. for k, v := range mp {
  8. if v > 1 {
  9. res = append(res, k)
  10. }
  11. }
  12. return res;
  13. }