first time I write on the SO, because he could not find solution myself. At the interview, I was given the task to write a method that checks the characters in the string to a unique.
Requirements: not using LINQ. Desirable: do not use additional data types (Dictionary, HashSet...etc. Arrays and lists Allowed)
Example:
"Hello" - return false; "Helo" - return true
My implementation:
static HashSet<char> charSet = new HashSet<char>();
static bool IsUniqueChar(string str)
{
foreach (char c in str)
{
charSet.Add(c);
}
return charSet.Count() == str.Length;
}
But it does not meet the requirements of data types, and is not the best performance... I also tried the approach with a dictionary:
static Dictionary<char,bool> charSetDictionary = new Dictionary<char,bool>();
static bool IsUniqueChar(string str)
{
try
{
foreach (char c in str)
{
charSetDictionary.Add(c,true);
}
}
catch
{
return false;
}
But he is no better than the previous. I will welcome any idea how to solve this task better? p.s
static void Main(string[] args)
{
Stopwatch sw = Stopwatch.StartNew();
IsUniqueChar("Hello");
sw.Stop();
Console.WriteLine("Elapsed={0}", sw.Elapsed); //~005044
}