Total accepted:19397 Total submissions:67937 difficulty:easy
You is playing the following Bulls and cows game with your friend:you write down a number and ask your friend to guess W Hat the number is. Each time your friend makes a guess, you provide a hint the indicates how many digits in said guess match your secret num ber exactly in both digit and position (called "bulls") and how many digits match the secret number but locate in the Wron G position (called "cows"). Your Friend would use successive guesses and hints to eventually derive the secret number.
For example:
Secret Number: " 1807" Friend's guess: "7810"
Hint:
1
Bull and
3
Cows. (The Bull is
8
, the cows is
0
,
1
and
7
.)
Write a function to return a hint according to the secret number and friend's guess, use to A
indicate the Bulls and c7/> to indicate the cows. In the above example, your function should return "1A3B"
.
Please note that both secret number and friend's guess may contain duplicate digits, for example:
Secret number: " 1123" Friend's guess: "0111"
In this case, the 1st
1
In friend's guess is a bull, the 2nd or 3rd
1
is a cow, and your function should return
"1A1B"
.
Assume that the secret number and your friend's guess only contain digits, and their lengths is always equal.
classSolution { Public: stringGethint (stringSecretstringguess) { intBulls =0; intCows =0; intnum[Ten] = {0 }; for(inti =0; I < guess.size (); i++) { if(Secret[i] = =Guess[i]) {Bulls= Bulls +1; } Else{Num[guess[i]-'0']++; } } for(inti =0; I < secret.size (); i++) { if(Secret[i]! = Guess[i] && Num[secret[i]-'0'] >0) {Cows++; Num[secret[i]-'0']--; } } Charbuff[ -]; sprintf (Buff,"%da%db", bulls, cows); returnBuff;} };
Javascript:
/** * @param {string} secret * @param {string} guess * @return {string}*/varGethint =function(Secret, guess) {vari; varBull=0; varCow=0; varSecretarr=NewArray (); varGuessarr=NewArray (); for(Iinchsecret) { if(secret[i]===Guess[i]) {Bull++; } if(Secretarr[number (Secret[i])]==NULL) {secretarr[number (Secret[i])]=0; } secretarr[number (Secret[i])++; if(Guessarr[number (guess[i])]==NULL) {guessarr[number (guess[i])]=0; } guessarr[number (Guess[i])++; } varSamenum=0; for(IinchSecretarr) { //if (Secretarr[i]===guessarr[i]) { //Samenum+=secretarr[i]; //} if(secretarr[i]!=NULL&& guessarr[i]!=NULL) { if(secretarr[i]>Guessarr[i]) {Samenum+=Guessarr[i]; } Else{samenum+=Secretarr[i]; } } } varRes= ""; varwp=samenum-Bull; Res=bull+ "A" +wp+ "B"; returnRes;};
Leetcode-299. Bulls and cows