VB2003下实现的KMP查找算法
增强型的模式匹配算法,KMP查找算法。全称是克努特-莫里斯-普拉特算法。是一种在一个串内查找第一个匹配子串位置的算法。之所以是增强型的,是应为它修改普通算法中失配的时候,被查找串的查找起始位置只向后移动一个单位的办法。通过首先分析匹配串的逻辑,给每一个项目位置加入一个权值。这样在失配的时候,就可以根据失配项目单位所对应的权值,顺移多个位置再次匹配。具体的算法可以参考《数据结构》一书。
现在我用VB.NET 2003实现这个算法。主函数KMPSearch进行实际的匹配操作。子函数KMPSearchGetNextArray负责计算匹配串每个项目单位对应的权值。
稍后推出使用VB2005泛型的KMP查找算法。
Public Shared Function KMPSearch(ByVal src As Array, ByVal key As Array) As Integer
Dim ret As Integer = 0
Dim arrNext() As Integer
Dim inti As Integer = 1
Dim intj As Integer = 1
If src Is Nothing OrElse key Is Nothing OrElse key.Length > src.Length Then
ret = -1
Else
arrNext = KMPSearchGetNextArray(key)
While inti <= src.Length AndAlso intj <= key.Length
If intj = 0 OrElse (Equals(src(inti - 1), key(intj - 1)) = True) Then
inti = inti + 1
intj = intj + 1
Else
intj = arrNext(intj)
End If
End While
If intj > key.Length Then
ret = inti - key.Length - 1
Else
ret = -1
End If
End If
Return ret
End Function
Private Shared Function KMPSearchGetNextArray(ByVal key As Array) As Integer()
Dim arrNext(key.Length) As Integer
Dim intj As Integer = 1
Dim intk As Integer = 0
arrNext(1) = 0
While intj < key.Length
If intk = 0 OrElse (Equals(key(intj - 1), key(intk - 1)) = True) Then
intj = intj + 1
intk = intk + 1
arrNext(intj) = intk
Else
intk = arrNext(intk)
End If
End While
Return arrNext
End Function