How to find the longest common prefix of all the words in a string with VB.NET

2 Answers

0 votes
Imports System
Imports System.Linq
Imports System.Text.RegularExpressions

Module Module1

    Function LongestCommonPrefix(input As String) As String
        If String.IsNullOrWhiteSpace(input) Then
            Return ""
        End If

        ' Split by non‑word characters (same as Java's split("\\W+"))
        Dim words = Regex.Split(input.ToLower(), "\W+").
                         Where(Function(w) w.Length > 0).
                         ToArray()

        If words.Length = 0 Then
            Return ""
        End If

        ' Start with the first word as the prefix
        Dim prefix As String = words(0)

        For i = 1 To words.Length - 1
            While Not words(i).StartsWith(prefix)
                prefix = prefix.Substring(0, prefix.Length - 1)
                If prefix = "" Then
                    Return ""
                End If
            End While
        Next

        Return prefix
    End Function

    Sub Main()
        Dim s1 = "The lowly inhabitants of the lowland were surprised to see the lower branches."
        Console.WriteLine("LCP: '" & LongestCommonPrefix(s1) & "'")

        Dim s2 = "unclear, uncertain, unexpected"
        Console.WriteLine("LCP: '" & LongestCommonPrefix(s2) & "'")
    End Sub

End Module



' run:
'
' LCP: ''
' LCP: 'un'
'

 



answered Mar 11 by avibootz
0 votes
Imports System
Imports System.Collections.Generic
Imports System.Text.RegularExpressions

Module Module1

    Function LongestCommonPrefix(input As String) As String
		If String.IsNullOrWhiteSpace(input) Then
			Return ""
		End If

		Dim rawWords = Regex.Split(input.ToLower(), "\W+")
		Dim words As New List(Of String)

		For Each w In rawWords
			If w.Length > 0 Then
				words.Add(w)
			End If
		Next

		If words.Count = 0 Then
			Return ""
		End If

		Dim prefix As String = words(0)

		For i = 1 To words.Count - 1
			While Not words(i).StartsWith(prefix)
				prefix = prefix.Substring(0, prefix.Length - 1)
				If prefix = "" Then
					Return ""
				End If
			End While
		Next

		Return prefix
	End Function


    Sub Main()
        Dim s1 = "The lowly inhabitants of the lowland were surprised to see the lower branches."
        Console.WriteLine("LCP: '" & LongestCommonPrefix(s1) & "'")

        Dim s2 = "unclear, uncertain, unexpected"
        Console.WriteLine("LCP: '" & LongestCommonPrefix(s2) & "'")
    End Sub

End Module



' run:
'
' LCP: ''
' LCP: 'un'
'

 



answered Mar 11 by avibootz

Related questions

...