[ create a new paste ] login | about

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

mohit_at_codepad - C, pasted on Jun 16:
#include <stdio.h>
#include <ctype.h>
#include <limits.h>

/// @brief Return first repeating character
/// @param [in] s string to search for
/// @ret '\0' If character not found
/// @ret First repeating character (a-z, A-Z, 0-9)
char findFirstRepeatingChar(const char *s) {
  char alreadyFound[1 << CHAR_BIT] = {0};
  // I am using hashing data structure alreadyFound
  // to decrease the cost of algorithm to O(N).
  // Instead if I use std::set or a BST (Binary search tree)
  // cost will increase to O(N logN)
  while(*s != '\0') {
//    if( alreadyFound[*s] ) return s
    if( alreadyFound[*s] && isalnum(*s) ) return *s;
    alreadyFound[*s++] = 1;
  }
  return '\0';
}

int main() {
  int testCaseNum;
  char testCases[][200] = {
    "This is a test.",
    "abcdefghi 1234 jklmnop 567890 zz",
    "abcdefghi 1234 jklmnop 567890 z",
    "",
    "abcabe",
    "a b c d should not output space",
    "x",
    "--",
    "aa"
  };
  for(testCaseNum = 0; testCaseNum < 9; ++testCaseNum) {
    printf( "Input = %s\n", testCases[testCaseNum ] );
    printf( "Output = %c\n"
             , findFirstRepeatingChar(testCases[testCaseNum ]) );
    printf( "\n" );
  }
  return 0;
}


Output:
Input = This is a test.
Output = i

Input = abcdefghi 1234 jklmnop 567890 zz
Output = z

Input = abcdefghi 1234 jklmnop 567890 z
Output = 

Input = 
Output = 

Input = abcabe
Output = a

Input = a b c d should not output space
Output = d

Input = x
Output = 

Input = --
Output = 

Input = aa
Output = a



Create a new paste based on this one


Comments: