Imports System
Imports System.Collections.Generic
Module SegmentTextVB
'
' Helper: check if a substring is in the dictionary.
' Uses a simple array of strings and linear search.
'
Function dict_contains(candidate As String, dict As String()) As Boolean
For Each word In dict
If candidate = word Then
Return True
End If
Next
Return False
End Function
'
' This function performs the segmentation and prints the result.
' It contains your original DP logic exactly as before.
'
Sub segment_text(text As String, dict As String())
Dim n As Integer = text.Length
' dp[i] = index j such that text[j:i] is a valid word and dp[j] is valid
Dim dp(n) As Integer
Dim valid(n) As Boolean
valid(0) = True ' empty prefix is valid
For i As Integer = 1 To n
valid(i) = False
For j As Integer = 0 To i - 1
' Check whether dp[j] contains a valid split point;
' if it does, it means the prefix text[0:j] can be segmented.
If valid(j) Then
' Create a lightweight substring representing text[j:i].
Dim len As Integer = i - j
Dim candidate As String = text.Substring(j, len)
' Verify whether this substring is a valid dictionary word.
If dict_contains(candidate, dict) Then
' Record that index j is the previous valid split before i.
' This means text[j:i] is a valid word and dp[j] was valid.
dp(i) = j
valid(i) = True
' Stop searching for other j values because we already found
' a valid segmentation ending at i.
Exit For
End If
End If
Next
Next
' If dp[n] is not valid, segmentation is impossible
If Not valid(n) Then
Console.WriteLine("No valid segmentation found.")
Return
End If
' Backtrack to recover words
Dim words As New List(Of String)()
Dim idx As Integer = n
While idx > 0
Dim j As Integer = dp(idx)
Dim len As Integer = idx - j
Dim w As String = text.Substring(j, len)
words.Add(w)
idx = j
End While
' Reverse the collected words
For i As Integer = 0 To (words.Count \ 2) - 1
Dim tmp As String = words(i)
words(i) = words(words.Count - 1 - i)
words(words.Count - 1 - i) = tmp
Next
' Print results
Console.WriteLine("Segmentation result:")
For Each w In words
Console.WriteLine(w)
Next
End Sub
Sub Main()
Dim text As String = "thisisatestfoo"
' Example dictionary
Dim dict As String() = {
"this", "is", "a", "test", "hello", "world", "foo", "bar"
}
' Call the segmentation function
segment_text(text, dict)
End Sub
End Module
'
'run:
'
'Segmentation result:
'this
'is'
'a'
'test'
'foo'
'