MCPcopy
hub / github.com/itcharge/AlgoNote / horspool

Function horspool

codes/python/04_string/string_horspool.py:2–15  ·  view source on GitHub ↗
(T: str, p: str)

Source from the content-addressed store, hash-verified

1# horspool 算法,T 为文本串,p 为模式串
2def horspool(T: str, p: str) -> int:
3 n, m = len(T), len(p)
4
5 bc_table = generateBadCharTable(p) # 生成后移位数表
6
7 i = 0
8 while i <= n - m:
9 j = m - 1
10 while j > -1 and T[i + j] == p[j]: # 进行后缀匹配,跳出循环说明出现坏字符
11 j -= 1
12 if j < 0:
13 return i # 匹配完成,返回模式串 p 在文本串 T 中的位置
14 i += bc_table.get(T[i + m - 1], m) # 通过后移位数表,向右进行进行快速移动
15 return -1 # 匹配失败
16
17# 生成后移位数表
18# bc_table[bad_char] 表示遇到坏字符可以向右移动的距离

Callers 1

string_horspool.pyFile · 0.85

Calls 1

generateBadCharTableFunction · 0.70

Tested by

no test coverage detected