1

I need some help with this function. I am trying to find the longest common string between 2 strings. Here is the function that I am currently using:

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

This works great on strings of up to around 600 words or so. If I try to compare strings with a larger word count than that it starts to throw system.outofmemoryexception. Obviously, this is hitting the memory pretty hard. Is there any way to fine tune this function or is there possibly another way of doing this that is more streamlined?

Tibrogargan
  • 4,508
  • 3
  • 19
  • 38
Zach Johnson
  • 2,047
  • 6
  • 24
  • 40
  • 1
    I was intrigued by your problem and thought maybe I'd see if I could tweak it a little bit, but I just ran it with a 6,000 word string and it worked fine, it even finished in just over a second which is pretty quick considering the strings were that long. That's ten times the length you got your memory exception with, so are you sure the problem doesn't lie elsewhere? Because your algorithm seems to work well imho... – soohoonigan Oct 08 '16 at 05:45
  • Thanks for the interest. I'm going to run some more tests today to see if it could be something else. It seems very sporadic. Working well sometimes, yet others throwing a memory error. I don't know if it's my imagination or not but it seems to start throwing more and more memory errors the more often I use it. Possibly a memory leak? Strange. – Zach Johnson Oct 08 '16 at 17:10

0 Answers0