-
Notifications
You must be signed in to change notification settings - Fork 31
/
isSubarray.py
62 lines (48 loc) · 1.47 KB
/
isSubarray.py
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
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
# isSubstring
from typing import Any, List, Sequence, TypeVar
T = TypeVar("T")
def isSubarray(longer: Sequence[T], shorter: Sequence[T]) -> int:
"""O(n)判断shorter是否为longer的子串."""
if len(shorter) > len(longer):
return False
if len(shorter) == 0:
return True
n, m = len(longer), len(shorter)
st = list(shorter) + list(longer)
z = zAlgo(st)
for i in range(m, n + m):
if z[i] >= m:
return True
return False
def zAlgo(seq: Sequence[Any]) -> List[int]:
n = len(seq)
if n == 0:
return []
z = [0] * n
j = 0
for i in range(1, n):
if j + z[j] <= i:
k = 0
else:
k = min(j + z[j] - i, z[i - j])
while i + k < n and seq[k] == seq[i + k]:
k += 1
if j + z[j] < i + z[i]:
j = i
z[i] = k
z[0] = n
return z
if __name__ == "__main__":
def randomCheck():
from random import randint
for _ in range(10000):
s = [randint(0, 10) for _ in range(100)]
t = [randint(0, 10) for _ in range(100)]
if isSubarray(s, t) != ("".join(map(str, t)) in "".join(map(str, s))):
print(s)
print(t)
print(isSubarray(s, t))
print("".join(map(str, t)) in "".join(map(str, s)))
raise ValueError
print("pass")
randomCheck()