我一直在 Excel (365) 中組合一個 UDF 來計算兩個字串之間的最長公共子序列(基于 python 
其他提示:
- 使用Option Explicit。
- 我使用MZ Tools for Excel。如果您是一個認真的程式員,我絕對建議您使用它。
uj5u.com熱心網友回復:
在盯著觀察視窗看太多時間之后......我有很多錯誤,我在應該是 y 的地方復制 x,在應該是 j 的地方輸入 i。
由于我找不到找到最長公共子序列的 VBA 示例,因此它是...
Public Function LCSMatch(ByVal x As Range, ByVal y As Range, Optional ByVal return_String As Boolean = False) As Variant
Dim xLen As Integer
Dim yLen As Integer
xLen = Len(x)
yLen = Len(y)
'Create Zeroed Array of xLen 1 x yLen 1 dimensions (intentional extra space).
ReDim L((xLen), (yLen)) 'indexing starts at 0.
For i = 0 To (xLen)
For j = 0 To (yLen)
L(i, j) = 0
Next j
Next i
'Build dynamic programming table from the bottom up...
'Note that L[xLen][yLen] will contain an integer equal to the length
'of the complete LCS.
'Note that L[i][j] contains the length of the lcs of x[0..i] and y[0..j]
For j = 0 To (yLen)
For i = 0 To (xLen)
If i = 0 Or j = 0 Then
L(i, j) = 0
ElseIf Mid$(x, i, 1) = Mid$(y, j, 1) Then
L(i, j) = L(i - 1, j - 1) 1
Else
L(i, j) = WorksheetFunction.Max(L(i - 1, j), L(i, j - 1))
End If
Next i
Next j
'Length of LCS
Dim LCSlen As Integer
LCSlen = L(xLen, yLen)
'Start from the right-most-bottom-most corner and store chars
'one by on in LCS
Dim LCS As String
LCS = ""
i = xLen
j = yLen
While i > 0 And j > 0
'If current character in x and y are same, then current char
'is part of the LCS. The L[xLen][yLen] is the location of the
'fist charachter we will PUSH onto the front of the LCS string
If Mid$(x, i, 1) = Mid$(y, j, 1) Then
LCSPart = Right$(LCS, Len(LCS))
LCS = Mid$(x, i, 1) & LCSPart
i = i - 1
j = j - 1
'GoTo Match
'If not same, then find the larger of the two lengths in L[][]
'then go in the direction of the larger value
ElseIf L(i - 1, j) > L(i, j - 1) Then
i = i - 1
Else
j = j - 1
End If
'Match:
Wend
MsgBox "Length of the LCS is " & LCSlen
MsgBox "LCS is " & LCS
If return_String Then
LCSMatch = LCS
Else
LCSMatch = LCSlen
End If
End Function
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/375352.html
下一篇:如果變數型別錯誤,則VBA跳過
