How to find the last repeated character in a string with C#

2 Answers

0 votes
using System;

class Program
{
    static int get_last_character_repeated(string s) { 
        int len = s.Length, ch_idx = -1;
          
        for (int i = 0; i < len; i++) { 
            for (int j = i + 1; j < len; j++) { 
                if (s[i] == s[j]) { 
                    ch_idx = i;
                    break;
                } 
            } 
        } 

        return ch_idx;  
    }  
    static void Main() {
        string s = "abcdxypcbadom"; 
       
        int i = get_last_character_repeated(s); 
      
        if (i == -1) 
            Console.WriteLine("Not found"); 
        else
            Console.WriteLine(s[i]); 
    }
}




/*
run:

d

*/

 



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

public static class StringUtils
{
    /// <summary>
    /// Finds the last repeated character in a string.
    ///
    /// Examples:
    /// "abca"          -> 'a'
    /// "abcbd"         -> 'b'
    /// "abcde"         -> null
    /// "abcdxypcbop"   -> 'p'
    /// "abcdxypcbadom" -> 'd'
    ///
    /// Time Complexity: O(n)
    /// Space Complexity: O(1)
    /// </summary>
    /// <param name="input">The input string.</param>
    /// <returns>
    /// The last repeated character, or null if none exists.
    /// </returns>
    public static char? FindLastRepeatedCharacter(string input)
    {
        if (string.IsNullOrEmpty(input))
        {
            return null;
        }

        // Frequency table for ASCII characters.
        int[] frequency = new int[256];

        // Count occurrences of each character.
        foreach (char ch in input)
        {
            frequency[ch]++;
        }

        // Traverse from right to left.
        for (int i = input.Length - 1; i >= 0; i--)
        {
            char ch = input[i];

            if (frequency[ch] > 1)
            {
                return ch;
            }
        }

        // No repeated character found.
        return null;
    }

    public static void Main()
    {
        Console.WriteLine(FindLastRepeatedCharacter("abca"));          
        Console.WriteLine(FindLastRepeatedCharacter("abcbd"));        

        char? result = FindLastRepeatedCharacter("abcde");
        Console.WriteLine(result ?? ' ');                              

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



/*
run:

a
b
 
p
d

*/

 



answered 5 days ago by avibootz
...