[ create a new paste ] login | about

Link: http://codepad.org/EAvhWu3U    [ raw code | output | fork ]

olnrao - C, pasted on Dec 11:
// 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;
}


Output:
1
2
3
4
5
6
7
8
9
10
11
12

DEBUG : Input Text = PearlPet, Length = 8
First Unique Character ("PearlPet") = 'a'
DEBUG : Input Text = LaxmiNarsimhaRaoOruganti, Length = 24
First Unique Character ("LaxmiNarsimhaRaoOruganti") = 'L'
DEBUG : Input Text = CodePad, Length = 7
First Unique Character ("CodePad") = 'C'
DEBUG : Input Text = CareerCup, Length = 9
First Unique Character ("CareerCup") = 'a'
DEBUG : Input Text = Opportunity, Length = 11
First Unique Character ("Opportunity") = 'r'
DEBUG : Input Text = Noon, Length = 4


Create a new paste based on this one


Comments: