Longest Repeated Substring

Longest repeated substring is an algorithm that finds the longest substring of a string that occurs at least twice.



									Public Shared Function LongestRepeatedSubstring(str As String) As String
	If String.IsNullOrEmpty(str) Then
		Return Nothing
	End If

	Dim N As Integer = str.Length
	Dim substrings As String() = New String(N - 1) {}

	For i As Integer = 0 To N - 1
		substrings(i) = str.Substring(i)
	Next

	Array.Sort(substrings)

	Dim result As String = ""

	For i As Integer = 0 To N - 2
		Dim lcs As String = LongestCommonString(substrings(i), substrings(i + 1))

		If lcs.Length > result.Length Then
			result = lcs
		End If
	Next

	Return result
End Function

Private Shared Function LongestCommonString(a As String, b As String) As String
	Dim n As Integer = Math.Min(a.Length, b.Length)
	Dim result As String = ""

	For i As Integer = 0 To n - 1
		If a(i) = b(i) Then
			result = result & a(i)
		Else
			Exit For
		End If
	Next

	Return result
End Function
								


Example

									Dim data = "the quick brown fox jumps over the lazy dog"
Dim value = LongestRepeatedSubstring(data)
								


Output

									the