⑴每个回文都有一个“中心”,当回文字符数为奇数时,中间的那个字符就是回文中心;但是当回文的字符数为偶数时,回文的中心是最中间的那两个字符,且这两个字符相同。
⑵对任意一个字符或者相同的两个连续字符,我们都可以假设它为回文的“中心”,向它的 左右两边扩展出尽可能长的回文。对于每种假设,我们都能得到一个回文,而最长回文必定由 其中的某个假设中得到!
现编写一个程序,在 Text1 中输入一串字符,单击“统计”按钮,在 Text2 中显示该字 符串中的最大的回文子串(长度相同时,输出最左边的子串)。请回答下列问题:
Dim n As Integer
Dim a(0 To 100) As String Private Sub Command1( Click)() Dim s As String
Dim left As Integer, right As Integer, i As Integer
Dim max As Integer, m As Integer, b1 As Integer
'变量b1用于记录回文子串的左端起点
Text2.Text = ""
s = Text1.Text n = Len(s)
For i = 1 To n
a(i) = Mid(s, i, 1) Next i
max = 0: left = 0: right = 0
For i = 1 To n left = i
right = i
m = longest(left, right) If m > max Then
b1 = i - m \ 2 max = m
End If left = i
right = i + 1
If a(left) = a(right) Then
m = longest(left, right) + 1
If m > max Then
①
max = m
End If
End If
Next i
For i = b1 To ②
Text2.Text = Text2.Text + a(i) Next i
End Sub
Function longest(left As Integer, right As Integer) As Integer
Dim p As Integer p = 1
Do While left > 1 And right < n And ③
left = left - 1 right = right + 1 p = p + 2
Loop
longest = p
End Function
① ② ③