我正在尝试创建一个应用程序,用于确定用户输入的字符串是否为回文序列。
是否可以不使用StrReverse,可能用于下一个循环。这就是我到目前为止所做的。
使用StrReverse工作一个:
Dim userInput As String = Me.txtbx1.Text.Trim.Replace(" ", "")
Dim toBeComparedWith As String = StrReverse(userInput)
Select Case String.Compare(userInput, toBeComparedWith, True)
Case 0
Me.lbl2.Text = "The following string is a palindrom"
Case Else
Me.lbl2.Text = "The following string is not a palindrom"
End Select
不工作:
Dim input As String = TextBox1.Text.Trim.Replace(" ", "")
Dim pallindromeChecker As String = input
Dim output As String
For counter As Integer = input To pallindromeChecker Step -1
output = pallindromeChecker
Next counter
output = pallindromeChecker
If output = input Then
Me.Label1.Text = "output"
Else
Me.Label1.Text = "hi"
End If
答案 0 :(得分:4)
虽然使用字符串反转工作,但它不是最理想的,因为你在字符串上迭代至少2次(因为字符串反转会创建一个字符串的副本,因为字符串在.NET中是不可变的)(加上额外的迭代次数)您的Trim
和Replace
来电。
然而,考虑回文的基本属性:字符串的前半部分反向等于字符串的后半部分。
检查回文的最佳算法只需迭代输入字符串的一半 - 将value[n]
与value[length-n]
n = 0 to length/2
进行比较。
在VB.NET中:
Public Shared Function IsPalindrome(value As String) As Boolean
' Input validation.
If value Is Nothing Then Throw New ArgumentNullException("value")
value = value.Replace(" ", "") // Note String.Replace(String,String) runs in O(n) time and if replacement is necessary then O(n) space.
' Shortcut case if the input string is empty.
If value.Length = 0 Then Return False ' or True, depends on your preference
' Only need to iterate until half of the string length.
' Note that integer division results in a truncated value, e.g. (5 / 2 = 2)...
'... so this ignores the middle character if the string is an odd-number of characters long.
Dim max As Integer = value.Length - 1
For i As Integer = 0 To value.Length / 2
If value(i) <> value(max-i) Then
' Shortcut: we can abort on the first mismatched character we encounter, no need to check further.
Return False
End If
Next i
' All "opposite" characters are equal, so return True.
Return True
End Function