2016-11-28 119 views
0

我想创建一个应用程序,它将确定用户输入的字符串是否是回文。Visual basic回文代码

是否有可能没有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 

回答

4

在使用字符串逆转的作品,这是最理想的,因为你至少2次全遍历字符串(因为字符串反转会创建一个字符串的副本,因为字符串在.NET中是不可变的)(加上您的TrimReplace调用的额外迭代)。

但是考虑回文的基本属性:字符串的前半部分与字符串的后半部分相反。

检查回文的最佳算法只需要遍历输入字符串的一半 - 比较value[n]value[length-n]对于n = 0 to length/2

在VB.NET:

Public Shared Function IsPalindrome(String value) As Boolean 

    ' Input validation. 
    If value Is Nothing Then Throw New ArgumentNullException("value") 
    value = value.Replace(" ", "") 

    Dim length As Integer = value.Length 
    ' Shortcut case if the input string is empty. 
    If 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 = length - 1 
    For i As Integer = 0 To 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 
+0

酷算法!非常简洁。我必须考虑的一点是,这适用于奇数字符串,因为整数类型将截短.5,导致将奇数长度除以2,并且中间的额外字符可以具有任何值。 – BobRodes

+0

@BobRodes正确,这就是为什么它更简单。 – Dai

+0

在VB.Net中,'3/2'被四舍五入为2,但是整数除法'3 \ 2'被截断为1.位移也起作用'length >> 1' – Slai