1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36
| class StrHash: MODS = [998244353, 1000000007]
class Hasher: BASE = 131
def __init__(self, s: str, m: int) -> None: self.m = m N = len(s) self.p = [1] * (N + 1) for i in range(1, N + 1): self.p[i] = self.p[i - 1] * self.BASE % m self.a = [0] * (N + 1) for i, c in enumerate(s, 1): self.a[i] = (self.a[i - 1] * self.BASE + ord(c)) % m
def query(self, l: int, r: int) -> int: return (self.a[r] - self.a[l - 1] * self.p[r - l + 1] % self.m + self.m) % self.m
def __init__(self, s: str) -> None: self.hashers = tuple(self.Hasher(s, m) for m in self.MODS)
def query(self, l: int, r: int) -> tuple[int, ...]: "[l, r)" return tuple(h.query(l + 1, r) for h in self.hashers)
class Solution: def strStr(self, haystack: str, needle: str) -> int: N, M = len(haystack), len(needle) target = StrHash(needle).query(0, M) h = StrHash(haystack) for i in range(N - M + 1): if h.query(i, i + M) == target: return i return -1
|