String Pattern Matching
Idea
String pattern matching finds occurrences of a pattern in a text. Classic algorithms: naive (BF), KMP, etc.
字符串模式匹配演示
此处可扩展为KMP等算法的匹配过程动画。
- 主串与模式串对齐
- next数组跳转演示
- 匹配/失配过程
Algorithms
Naive (Brute Force)
- Align pattern and text, compare sequentially
- Time , text length, pattern length
KMP
- Uses prefix table (next array) to avoid re-checking
- Time
Scenarios
- Text editor find/replace
- DNA sequence analysis
- Search/retrieval, data mining
Pseudo-code
Naive:
for i = 0 to m-n:
for j = 0 to n-1:
if S[i+j] != P[j]:
break
if j == n:
return i // match
return -1
KMP (simplified):
build next array
i = 0, j = 0
while i < m:
if S[i] == P[j]:
i++, j++
if j == n: return i-n // match
else if j > 0:
j = next[j-1]
else:
i++
return -1
Complexity
- Naive:
- KMP:
Exercises
Exercise 1
Explain KMP idea and its advantage.
参考答案
思路:next 避免重复比较。
步骤:
- 用 next 跳过已匹配前缀
- 时间
答案:next 让主串不回溯,提效。
Exercise 2
Time complexity of naive vs KMP?
参考答案
思路:直接比较。
步骤:
- 朴素
- KMP
答案:朴素 ,KMP 。
Past exam
2022·408
KMP 如何避免主串指针回溯?
参考答案
思路:next 数组跳转。
步骤:
- 匹配失败主串不回溯
- 模式串按 next 跳
答案:用 next 跳转模式串,主串不回溯。