Leetcode 299: Bulls and Cows
You are playing the followingBulls and Cowsgame with your friend: You write down a number and ask your friend to guess what the number is. each time your friend makes a guess, you provide a hint that indicates how many digits in said guess match your secret number exactly in both digit and position (called "bulls ") and how to adjust digits match the secret number but locate in the wrong position (called "cows "). your friend will 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 are
0
,
1
And
7
.)
Write a function to return a hint according to the secret number and friend's guess, useA
To indicate the bulls andB
To indicate the cows. In the above example, your function shocould return"1A3B"
.
Please note that both secret number and friend's guess may contain in 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 shoshould return
"1A1B"
.
You may assume that the secret number and your friend's guess only contain digits, and their lengths are always equal.
Credits:
Special thanks to @ jeantimexico for adding this problem and creating all test cases.
Subscribeto see which companies asked this question
// You and your friends are playing the following guess number game (BullsandCows): you write the next 4-digit mysterious number and ask your friends to guess it. // each time your friend guesses a number, you give a prompt to tell him how many numbers are in the correct position (called "bulls" Bull ), // and how many numbers are in the wrong position (called "cows" cows). Your friends use these tips to find the mysterious number. Class Solution {public: string getHint (string secret, string guess) {int aCnt = 0; // Number of bulls int bCnt = 0; // number of cows vector
SVec (10, 0); vector
GVec (10, 0); if (secret. length ()! = Guess. length () | secret. empty () return "0A0B"; for (int I = 0; I