Saturday, August 20, 2011

First non repeating character in a string

Problem taken from
Write a function that takes an input string and returns the first character from the string that is not repeated later in the string. For instance, the two letters “d” and “f” in the input string “aabcbcdeef” are non-repeating, and the function should return “d” since “f” appears later in the string. The function should return some indication if there are no non-repeating characters in the string.

Here is my solution ::
-- I am going over the length of the string, breaking whenever I find a non-repeating char.
For ease of searching a char, I am copying the entire string, expect the "char" I am currently looking at to a new string and search for that char in the new appended string.
If found implies it's repeated, else non-repeating

<pre class="prettyprint">
int main () {

    char str[80];
    char str_a[80];
    int len, i;
    char c;

    printf("Please enter the string to find non-repeating char\n");
    len = strlen(str);

    for (i = 0; i < len ; i++) {
        c = str[i];
       //copy rest of the string except char 'c' into another
        memcpy(&str_a[0] , &str[0], i); 
        memcpy(&str_a[i] , &str[i+1], (len-i-1));
        if (!strchr(str_a, c)) {
            printf("First non repeating char in string : \"%c\"\n",c);
    if (i == len)
        printf("Non repeating char not found in given string\n");

No comments: