using System;
using System.Collections.Generic;
public static class StringUtils
{
/// <summary>
/// Finds the first repeated character in a string.
///
/// Examples:
/// "abca" -> 'a'
/// "abcbd" -> 'b'
/// "abcde" -> null
/// "abcdxypcbop" -> 'c'
///
/// Time Complexity: O(n)
/// Space Complexity: O(n)
/// </summary>
/// <param name="input">The input string.</param>
/// <returns>
/// The first repeated character, or null if no repeated character exists.
/// </returns>
public static char? FindFirstRepeatedCharacter(string input)
{
if (string.IsNullOrEmpty(input)) {
return null;
}
var seen = new HashSet<char>();
foreach (char ch in input)
{
// HashSet.Add() returns false if the character
// already exists in the set.
if (!seen.Add(ch)) {
return ch;
}
}
// No repeated character found.
return null;
}
public static void Main()
{
Console.WriteLine(FindFirstRepeatedCharacter("abca"));
Console.WriteLine(FindFirstRepeatedCharacter("abcbd"));
Console.WriteLine(FindFirstRepeatedCharacter("abcde"));
Console.WriteLine(FindFirstRepeatedCharacter("abcdxypcbop"));
}
}
/*
run:
a
b
c
*/