1

我需要一些有关此功能的帮助。我试图找到 2 个字符串之间最长的公共字符串。这是我目前正在使用的功能:

Public Shared Function LCS(str1 As Char(), str2 As Char())
    Dim l As Integer(,) = New Integer(str1.Length - 1, str2.Length - 1) {}
    Dim lcs__1 As Integer = -1
    Dim substr As String = String.Empty
    Dim [end] As Integer = -1

    For i As Integer = 0 To str1.Length - 1
        For j As Integer = 0 To str2.Length - 1
            If str1(i) = str2(j) Then
                If i = 0 OrElse j = 0 Then
                    l(i, j) = 1
                Else
                    l(i, j) = l(i - 1, j - 1) + 1
                End If
                If l(i, j) > lcs__1 Then
                    lcs__1 = l(i, j)
                    [end] = i

                End If
            Else
                l(i, j) = 0
            End If
        Next
    Next

    For i As Integer = [end] - lcs__1 + 1 To [end]
        substr += str1(i)
    Next

    Return substr
End Function

这对大约 600 个单词左右的字符串非常有效。如果我尝试比较字数大于字数的字符串,它会开始抛出system.outofmemoryexception。显然,这对内存造成了很大的打击。有没有办法微调这个功能,或者是否有另一种更精简的方法?

4

0 回答 0