查找给定哈希值的子串
难度:
标签:
题目描述
代码结果
运行时间: 92 ms, 内存: 18.4 MB
/*
* Solution Approach:
* 1. Utilize Java Streams to find the substring with the given hashValue.
* 2. Convert characters to values and use IntStream to calculate the hash.
* 3. Find the first matching hash using the Streams API.
*/
import java.util.stream.IntStream;
public class SolutionStream {
public String subStringWithGivenHash(String s, int power, int modulo, int k, int hashValue) {
return IntStream.rangeClosed(0, s.length() - k)
.filter(i -> hash(s.substring(i, i + k), power, modulo) == hashValue)
.mapToObj(i -> s.substring(i, i + k))
.findFirst()
.orElse("");
}
private int hash(String sub, int power, int modulo) {
int hash = 0;
long powerFactor = 1;
for (int i = 0; i < sub.length(); i++) {
hash = (int) ((hash + (sub.charAt(i) - 'a' + 1) * powerFactor) % modulo);
powerFactor = (powerFactor * power) % modulo;
}
return hash;
}
}
解释
方法:
此题解使用滑动窗口和哈希表来检索特定哈希值的子串。首先,代码创建一个映射mp,用于快速获取字符对应的字母表位置。使用数组f和g来计算子串的哈希值,数组h存储power的幂次模modulo的结果,用于优化计算。数组f从后向前计算当前窗口的哈希值。如果初始窗口的哈希值符合要求,直接返回该子串。否则,使用数组g从前向后递增地添加字符,并重新计算哈希值,检查每次添加后的新窗口哈希值是否符合要求。这种方法有效地避免了重复的计算,通过动态调整窗口来寻找正确的子串。
时间复杂度:
O(n)
空间复杂度:
O(k)
代码细节讲解
🦆
在计算哈希值时,为什么选用了模运算,这里的`modulo`参数具体起到了什么作用?
▷🦆
数组`h`用于存储`power`的幂次模`modulo`的结果,这样做的主要目的是什么?
▷🦆
题解中提到,如果初始窗口的哈希值符合要求就直接返回该子串,这里的初始窗口是如何定义的?
▷🦆
在动态调整窗口时,使用了两个数组`f`和`g`来计算哈希值,能否详细解释这两个数组的具体作用?
▷