// Find First Non-Repeated/Unique Character in a string
// Assumptions:
// - English Alphabets only (A-Z, a-z)
// - Case Insensitive
// - Max String Length < MAX_INT (or INT_MAX)
//
#define DEBUG_PRINT
#define MAX_ALPHABET 26
#define IS_BIT_SET(bv, bx) (!!((bv) & (2 << (bx))))
#define SET_BIT(bv, bx) ((bv) |= (2 << (bx)))
#include <stdio.h>
void FindUniqueChar(char *pText);
int main(int argc, char *args[])
{
printf("\n");
FindUniqueChar("PearlPet"); // 'a'
FindUniqueChar("LaxmiNarsimhaRaoOruganti"); // 'L'
FindUniqueChar("CodePad"); // 'C'
FindUniqueChar("CareerCup"); // 'a'
FindUniqueChar("Opportunity"); // 'r'
FindUniqueChar("Noon"); // ?
return 0;
}
int CharBaseIndex(char ch)
{
if (ch >= 'A' && ch <= 'Z') return ch - 'A';
if (ch >= 'a' && ch <= 'z') return ch - 'a';
return -1;
}
void FindUniqueChar(char *pText)
{
int errorCode;
int nText = strlen(pText);
int chBits = 0, chBitsRepeated = 0;
int chIndexQ[MAX_ALPHABET] = {-1};
int nIndexQ = 0;
int i, chx;
char ch;
#ifdef DEBUG_PRINT
printf("DEBUG : Input Text = %s, Length = %d\n", pText, nText);
#endif
for (i = 0; i < nText; i++)
{
ch = pText[i];
chx = CharBaseIndex(ch);
if (chx < 0)
{
errorCode = -1; // Unknown character
goto Exit;
}
// Did we see this character before?
if (IS_BIT_SET(chBits, chx))
{
SET_BIT(chBitsRepeated, chx);
continue;
}
SET_BIT(chBits, chx);
chIndexQ[nIndexQ++] = i;
}
for (i = 0; i < nIndexQ; i++)
{
ch = pText[chIndexQ[i]];
chx = CharBaseIndex(ch);
// Is this unique?
if (IS_BIT_SET(chBitsRepeated, chx)) continue;
printf("First Unique Character (\"%s\") = '%c'\n", pText, ch);
break;
}
errorCode = 0;
Exit:
return;
}