Monday, December 25, 2006

First Non-Repeated Character from a UNICODE String using Hash Table

the only difference here is the input string can be UNICODE (65000 characters) instead of ASCII Code (256 characters) so using a hash table makes more sense


public static char FirstNonRepeatedHash(string stringToCheck)
{
Hashtable cHash = new Hashtable();
int length = stringToCheck.Length;
int i = 0;
bool hashPresent = false;
char charToReturn = '\0';

for (i = 0; i < length; i++)
{
hashPresent = cHash.Contains(stringToCheck[i]);
if (hashPresent)
{
cHash[stringToCheck[i]] = 1 + Convert.ToInt32(cHash[stringToCheck[i]]);
}
else
{
cHash.Add(Convert.ToChar(stringToCheck[i]), 1);
}

}

for (i = 0; i < length; i++)
{
if (Convert.ToInt32(cHash[stringToCheck[i]]) ==1 )
{
charToReturn = stringToCheck[i];
break;
}
}
return charToReturn;
}

First Non repeated Character in a String using an Array

Here is how to find the first non repeated character in an a string using an array
the assumption is the String is ASCII other wise check for the hash table function

For example If the input is "TEETOTALAR" The First non repeated Character is "O"


public static char FirstNonRepeatedArray(string stringToCheck)
{
int length = stringToCheck.Length;
int i = 0;
int[] intCollection = new int[256];
char returnChar = '\0';

for (i = 0; i < length; i++)
{
intCollection[stringToCheck[i]] = intCollection[stringToCheck[i]] + 1;
}
for (i = 0; i < length; i++)
{
if (intCollection[stringToCheck[i]] == 1)
{
returnChar = stringToCheck[i];
break;
}
}
return returnChar;
}