Saturday, October 19, 2013

[Amazon Written test] Run Length Encoding

Write a function to convert AAABBBBBCDEHH to A3B5CDEH2 and a method to generate the original string back.

1 comment:

  1. This is standard run length encoding algorithm.

    #include
    #include
    #include
    #include
    #define MAX_R_LEN 50

    char *encode(char *src)
    {
    int i=0,j=0,k,rLen;
    char count[MAX_R_LEN];
    int len=strlen(src);
    char *dest=(char*)malloc(sizeof(char)*(2*len+1));
    for(i=0;i1)
    {
    sprintf(count, "%d",rLen);
    for(k=0;*(count+k);k++,j++)
    {
    dest[j]=count[k];
    }
    }
    }
    dest[j]='\0';
    return dest;
    }
    int main()
    {
    char str[]="AAABBBBBCDEHH";
    printf("%s ", encode(str));
    getch();
    return 0;
    }

    ReplyDelete