【问题标题】:Visual basic palindrome codeVisual Basic 回文码
【发布时间】:2018-05-29 01:38:40
【问题描述】:

我正在尝试创建一个应用程序,该应用程序将确定用户输入的字符串是否为回文。

是否可以不使用 StrReverse,可能使用 for next 循环。这就是我到目前为止所做的。

使用 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

【问题讨论】:

    标签: vb.net


    【解决方案1】:

    虽然使用字符串反转有效,但它不是最理想的,因为您要对字符串进行至少 2 次完整的迭代(因为字符串反转会创建一个字符串的副本,因为字符串在 .NET 中是不可变的)(加上额外的迭代为您的 @ 987654321@ 和 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
    

    【讨论】:

    • 酷算法!非常简洁。我必须考虑的一点是,这适用于奇数字符串,因为 Integer 类型会截断 .5 导致奇数长度除以 2,而中间的多余字符可以具有任何值。
    • @BobRodes 正确,这就是它更简单的原因。
    • 在 VB.Net 中 3 / 2 被舍入为 2,但整数除法 3 \ 2 被截断为 1。位移也可以工作 length &gt;&gt; 1
    • 或许可以考虑将验证简化为If String.IsNullOrWhiteSpace(value) Then Throw New ArgumentException(value)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-05-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-10-26
    相关资源
    最近更新 更多