VB.NET2005通过泛型实现的KMP查找算法
增强型的模式匹配算法,KMP查找算法VB.NET 2005泛型实现。也不知道用的对不对,但是个人感觉好像是对的。不过做测试的时候发现如果是字符串(字符数组)的匹配,用KMP算法比.NET自己的String.IndexOf还要慢。不知道.NET怎么做的,可能也是KMP算法吧。
和2003版的一样,主函数KMPSearch进行实际的匹配操作。子函数KMPSearchGetNextArray负责计算匹配串每个项目单位对应的权值。只不过加入了(Of T As IComparable(Of T))泛型约束。
Public Shared Function KMPSearch(Of T As IComparable(Of T))(ByVal src() As T, ByVal key() As T) 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(Of T)(key)
While inti <= src.Length AndAlso intj <= key.Length
If intj = 0 OrElse src(inti - 1).Equals(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(Of T As IComparable(Of T))(ByVal key() As T) 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 key(intj - 1).Equals(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