leetcode 299. Bulls and Cows

Orignal question can be found here.

My solution is as follows:

        unsigned int secret_len = strlen(secret), guess_len = strlen(guess);
        unsigned int acnt = 0, bcnt = 0;
        int* guess_flag = (int*)malloc(sizeof(int)*guess_len);
        int* secret_flag = (int*)malloc(sizeof(int)*secret_len);
        char* result = (char*)malloc(sizeof(char)*16);
        int i = 0, j = 0;

        for(i=0; i<guess_len; ++i)
                guess_flag[i] = 0;
        for(i=0; i<secret_len; ++i)
                secret_flag[i] = 0;

        i = 0;
        while(i<secret_len && i<guess_len)
        {
                if(secret[i] == guess[i])
                {
                        ++acnt;
                        guess_flag[i]=1;
                        secret_flag[i]=1;
                }
                ++i;
        }

        for(i=0; i<guess_len; ++i)
        {
                if(guess_flag[i] == 1)
                        continue;
                for(j=0; j<secret_len; ++j)
                {
                        if(guess[i] == secret[j] && secret_flag[j] == 0)
                        {
                                ++bcnt;
                                secret_flag[j]=1;
                                break;
                        }
                }
        }

        free(guess_flag);
        free(secret_flag);

        sprintf(result,"%dA%dB",acnt,bcnt);
        return result;

Leave a Reply

Your email address will not be published. Required fields are marked *