题意:
解题思路:
1. 滑动窗口+哈希表O(n)
2. 从0 开始每次截取字符串10个长度放入哈希表中;
3. 从前往后扫描,出现重复串,将其哈希值++;
4. 最后统计大于1的哈希值;
PHP代码实现:
class Solution {
/**
* @param String $s
* @return String[]
*/
function findRepeatedDnaSequences($s) {
$map = [];
for ($i = 0; $i + 10 <= strlen($s); $i++) {
$map[substr($s, $i, 10)]++;
}
$res = [];
foreach ($map as $k => $v) {
if ($v > 1) array_push($res, $k);
}
return $res;
}
}
go代码实现:
func findRepeatedDnaSequences(s string) []string {
mp := make(map[string]int)
for i := 0; i + 10 <= len(s); i++ {
mp[s[i:i+10]]++
}
res := make([]string, 0)
for k, v := range mp {
if v > 1 {
res = append(res, k)
}
}
return res;
}