字符串相似度算法

Private Function Min(ParamArray Num()) As Integer
    Dim tN As Integer, i As Integer
    If UBound(Num) = -1 Then Min = -999: Exit Function
    tN = Num(0)
    For i = 1 To UBound(Num)
        If Num(i) < tN Then tN = Num(i)
    Next
    Min = tN
End Function

Public Function CacuDistance(ByVal s1 As String, ByVal s2 As String) As Integer
    Dim i As Integer, b1$(), b2$(), n1 As Integer, n2 As Integer, j As Integer
    Dim tP1 As Integer, tP2 As Integer, tA() As Integer, tN1 As Integer, tN2 As Integer, tN3 As Integer
    
    n1 = Len(s1)
    n2 = Len(s2)
    
    ReDim b1(n1 - 1)
    For i = 1 To n1
        b1(i - 1) = Mid$(s1, i, 1)
    Next
    
    ReDim b2(n2 - 1)
    For i = 1 To n2
        b2(i - 1) = Mid$(s2, i, 1)
    Next
    
    If n1 = 0 Then CacuDistance = n2: Exit Function
    If n2 = 0 Then CacuDistance = n2: Exit Function
    
    j = Min(n1, n2) - 1
    
    tP1 = -1
    tP2 = -1

    For i = 0 To j
        If b1(i) <> b2(i) Then
            tP1 = i
            Exit For
        End If
    Next

    If tP1 = -1 Then CacuDistance = Abs(n1 - n2): Exit Function

    For i = 0 To j - tP1
        If b1(n1 - i - 1) <> b2(n2 - i - 1) Then
            tP2 = i
            Exit For
        End If
    Next

    If tP2 = -1 Then CacuDistance = Abs(n1 - n2): Exit Function

    ReDim tA(n1 - tP1 - tP2)
    
    For i = 0 To UBound(tA)
        tA(i) = i
    Next

    For i = 0 To n2 - tP1 - tP2 - 1
        tN1 = tA(0)
        tN2 = tN1 + 1
        For j = 1 To UBound(tA)
            If b1(n1 - tP2 - j) = b2(n2 - tP2 - i - 1) Then
                tN3 = tN1
            Else
                tN3 = Min(tA(j), tN1, tN2) + 1
            End If
            tA(j - 1) = tN2
            tN2 = tN3
            tN1 = tA(j)
        Next
        tA(UBound(tA)) = tN2
    Next

    CacuDistance = tA(UBound(tA))
End Function

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值