Advertisement
Guest User

Untitled

a guest
Jun 6th, 2016
1,036
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 0.79 KB | None | 0 0
  1. #include <limits.h>
  2.  
  3. char findFirstNonRepeating(char* str)
  4. {
  5.     char count[26] = {0}; // O(1)
  6.     char index[26] = {-1}; // O(1)
  7.  
  8.     // scan the string - O(n)
  9.     for (int i = 0; str[i] != '\0'; ++i)
  10.     {
  11.         char c = str[i];
  12.  
  13.         ++count[c - 'A'];
  14.  
  15.         // if this character has not been found yet, mark it as found
  16.         if (index[c - 'A'] == -1)
  17.             index[c - 'A'] = i;
  18.     }
  19.  
  20.     // find the minimum index at which count is 1. This is O(1).
  21.     int minIndex = INT_MAX;
  22.     for (int i = 0; i < 26; ++i)
  23.     {
  24.         if (index[i] != -1)
  25.         {
  26.             if (count[i] == 1 && index[i] < minIndex)
  27.                 minIndex = index[i];
  28.         }
  29.     }
  30.  
  31.     if (minIndex == INT_MAX)
  32.         return '\0';
  33.     else
  34.         return str[minIndex];
  35. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement