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

2 Answers

0 votes
Imports System
                 
Public Module Module1
    Public Function get_last_character_repeated(s As String) As Integer
        Dim len As Integer = s.Length - 1
        Dim ch_idx As Integer = -1
            
        For i As Integer = 0 To len
            For j As Integer = i + 1 To len
                If (s(i) = s(j)) Then
                    ch_idx = i
                    Exit For
                End If
            Next
        Next
        return ch_idx
    End Function 

    Public Sub Main()
        Dim s As String = "abcdxypcbadom"
         
        Dim i As Integer = get_last_character_repeated(s)
        If (i = -1) Then
            Console.WriteLine("Not found")
        else
            Console.WriteLine(s(i))
        End If
    End Sub
End Module
 
 
' run:
'
' d
'

 



answered Jan 25, 2020 by avibootz
edited 5 days ago by avibootz
0 votes
Imports System

Module Program

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

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

        ' Frequency table for ASCII characters.
        Dim frequency(255) As Integer

        ' Count occurrences of each character.
        For Each ch As Char In input
            frequency(Convert.ToInt32(ch)) += 1
        Next

        ' Traverse from right to left.
        For i As Integer = input.Length - 1 To 0 Step -1
            Dim ch As Char = input(i)

            If frequency(Convert.ToInt32(ch)) > 1 Then
                Return ch
            End If
        Next

        ' No repeated character found.
        Return Nothing

    End Function

    Sub Main()

        Console.WriteLine(FindLastRepeatedCharacter("abca"))         
        Console.WriteLine(FindLastRepeatedCharacter("abcbd"))         

        Dim result As Char? = FindLastRepeatedCharacter("abcde")
        Console.WriteLine(If(result.HasValue, result.Value, " "c))    

        Console.WriteLine(FindLastRepeatedCharacter("abcdxypcbop"))   
        Console.WriteLine(FindLastRepeatedCharacter("abcdxypcbadom")) 

    End Sub

End Module
 

 
' run:
'
' a
' b
'  
' p
' d
' 
'

 



answered 5 days ago by avibootz
...