This is really a mind twisting question. But if you dint give a try to solve this , you may think that its so simple.
This was asked in one of my interview.
now lets see how to solve this
Method call : GetFirstNonRepeatedChar("abcdab");
private char GetFirstNonRepeatedChar(string value)
{
// declare a character array.
char[] cArr = null;
try
{
// load the string to char array.
cArr = value.ToCharArray();
for (int i = 0; i < cArr.Length; i++)
{
// count to track all comparison has over
int count = 0;
for (int j = 0; j < cArr.Length; j++)
{
// avoids to comparison for same character
if (i != j)
{
// if repeated then come out of the inner loop
if (cArr[i] == cArr[j])
{
break;
}
else
{
// increament the count for each non repeatable comparison
count = count + 1;
// if the count reaches the char array length - 1
// and you are inside the for loop then the current value
// is the first non repeated character.
if (count == cArr.Length -1)
{
return cArr[i];
}
}
}
}
}
return '0'; // if no non repeated char is fount
}
catch (Exception)
{
throw;
}
}
Answer : c
No comments:
Post a Comment