How to find the first repeated character in a string with VB.NET

1 Answer

0 votes
Imports System
Imports System.Collections.Generic

Module Program

    ''' <summary>
    ''' Finds the first repeated character in a string.
    '''
    ''' Examples:
    ''' "abca"         -> "a"c
    ''' "abcbd"        -> "b"c
    ''' "abcde"        -> Nothing
    ''' "abcdxypcbop"  -> "c"c
    '''
    ''' Time Complexity: O(n)
    ''' Space Complexity: O(n)
    ''' </summary>
    ''' <param name="input">The input string.</param>
    ''' <returns>
    ''' The first repeated character, or Nothing if no repeated character exists.
    ''' </returns>
    Function FindFirstRepeatedCharacter(input As String) As Char?

        If String.IsNullOrEmpty(input) Then
            Return Nothing
        End If

        Dim seen As New HashSet(Of Char)()

        For Each ch As Char In input

            ' HashSet.Add returns False if the character
            ' already exists in the set.
            If Not seen.Add(ch) Then
                Return ch
            End If

        Next

        ' No repeated character found.
        Return Nothing

    End Function

    Sub Main()

        PrintResult("abca")
        PrintResult("abcbd")
        PrintResult("abcde")
        PrintResult("abcdxypcbop")

    End Sub

    Private Sub PrintResult(input As String)

        Dim result As Char? = FindFirstRepeatedCharacter(input)

        If result.HasValue Then
            Console.WriteLine(result.Value)
        Else
            Console.WriteLine("No repeated character")
        End If

    End Sub

End Module


' run:
'
' a
' b
' No repeated character
' c
'

 



answered Sep 4, 2022 by avibootz
edited 6 days ago by avibootz
...