例如:
分析:如果词典中的单词数量比较少,我们可以采取将第i个单词与第j个单词拼接成“新单词”并在字典中查找,但如果词典中单词数量多(如12000个)此种方法速度慢,我们发现词典中的单词是有序排列,可以加快查找复合单词的速度,本题的算法策略是:对第i个单词,从第j(j=i+1)个开始判断,如果第j个单词前半部分(长度为第i个单词的长度)跟第i个单词一致,则在词典中查找第j个单词的后半部分。如果找到,则为一个复合单词。
编写vb程序,寻找词典中所有复合单词并输出显示。运行程序,在列表框list1中显示从词典数据库中导入的单词,单击“统计”按钮command1,在列表框list2中按降序显示该词典中所有复合单词。程序运行界面如图所示。
Dim conn As New ADODB.Connection
Dim rs As New ADODB.Recordset
Dim n As Integer
Dim a(1 To 200) As String
Function search(key As String) As Boolean
i = 1: j = n
Do While i <= j
m = Int(i + (j - i) / 2)
If key = a(m) Then
search = True: Exit Do
ElseIf key > a(m) Then
i = m + 1
Else
j = m - 1
End If
Loop
End Function
Private Sub Command1_Click()
Dim i As Integer, j As Integer, temp2 As String
Dim out(0 To 100)
For i = 1 To n
For j = i + 1 To n
If a(i) = Mid(a(j), 1, Len(a(i))) Then
If search(temp2) = True Then
cnt = cnt + 1
k = cnt
Do While a(j) > out(k) And k > 0 '找到a(j)应该插入的位置k
k = k - 1
Loop
For p = cnt To k + 1 Step -1 'k到末尾元素均后移一位
out(p) = out(p - 1)
Next p
End If
End If
Next j
Next i
For i = 1 To cnt
List2.AddItem out(i)
Next i
End Sub
Private Sub Form_Load()
Dim i As Integer
连接字典数据库
打开数据库中字典数据表,代码略
n = 0
Do While Not rs.EOF
n = n + 1
a(n) = rs/Fields("words")
rs/MoveNext
Loop
关闭数据连接,代码略
List1.Clear
For i = 1 To n
List1.AddItem a(i) '在列表框List1中显示单词
Next i
End Sub