概念:将字符串映射为一个Hash值
注意:做到严格的进行计数的「哈希表」就不能是以 String
作为 key
,只能使用 Integer
(也就是 hash 结果本身)作为 key
。因为 Java 中的 String
的 hashCode
实现是会对字符串进行遍历的,这样哈希计数过程仍与长度有关,而 Integer
的 hashCode
就是该值本身,这是与长度无关的。
class Solution {
int N = (int)1e5+10, P = 131313;
int[] h = new int[N], p = new int[N];
public void getHash(int l,int r,String s){
int n = s.length();
p[0] = 1;
for (int i = 1; i <= n; i++) {
h[i] = h[i - 1] * P + s.charAt(i - 1); //计算字符串hash(前缀和)
p[i] = p[i - 1] * P; //p数组存储i处的字符的权重
}
}
//删除区间内某个值hash的变化
public void deletePos(int l,int r,int pos){
return h[pos + 1,r] + h[l,pos - 1] * p[r - pos];
}
public List<String> findRepeatedDnaSequences(String s) {
List<String> ans = new ArrayList<>();
Map<Integer, Integer> map = new HashMap<>();
for (int i = 1; i + 10 - 1 <= n; i++) {
int j = i + 10 - 1;
int hash = h[j] - h[i - 1] * p[j - i + 1];
int cnt = map.getOrDefault(hash, 0);
if (cnt == 1) ans.add(s.substring(i - 1, i + 10 - 1));
map.put(hash, cnt + 1);
}
return ans;
}
}