How to calculate time complexity of this function which checks if a string
has all unique characters?
The book "Cracking the Coding Interview", and this Stack Overflow question
discusses a function which determines if a string contains all unique
characters. The book's answer which uses bit shifting is in the question
link ( please see the top answer on the page) and I won't repeat it here.
The Java answer has a O(N) complexity, and I can't get my head around what
O(N) actually means. I actually want to find out what is the time
complexity for this implementation that I wrote just now. Is it O(N) ? How
does one figure the complexity?
static void Main(string[] args)
{
string stringToCheck ;
bool hasAllUniqueChars = false;
stringToCheck = "Test";
hasAllUniqueChars = CheckForUniqueChars(stringToCheck);
Console.WriteLine("String is Unique {0}", hasAllUniqueChars);
Console.Read();
}
private static bool CheckForUniqueChars(string stringToCheck)
{
for (int i = 0; i < stringToCheck.Length - 1; i++)
{
for (int j = i; j < stringToCheck.Length - 1; j++)
{
if (Char.ToUpper(stringToCheck.ElementAt(i)) ==
Char.ToUpper(stringToCheck.ElementAt(j+1)))
{
return false;
}
}
}
return true;
}
This returns false for Test,test,Hello, and true for SuperMan,SpiderMan
and Sponge and works fine.
Thank you
No comments:
Post a Comment