题目:
You are playing the following Bulls and Cows game 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 many 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, use A to indicate the bulls and B 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”.
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 @jeantimex for adding this problem and creating all test cases.
Subscribe to see which companies asked this question
题意:
小伙伴们玩一个游戏,让小伙伴去猜一个数字,然后你给出一个提示。这个提示包括两个内容,第一是猜的数字与原来的数字在某个位置上一样,这个的个数需要告诉小伙伴。还有一个就是数字猜对了不过不在这个位置上。比如”1123”,小伙伴猜了”0111”,那么只有第二个位置上的1是猜对了,然后有个1是数字对了但位置不对。所以你需要给出的提示是1A1B。
思路:
对应的位置数字一样没什么话讲,只需要查看是否一样即可。主要讨论的是数字一样,但位置不同。当当前位置上两个数字不一样时,统计secret各个数字出现的次数,也统计下小伙伴猜的数字各个数字出现的次数。比如除了两个位置上一样的数外,原来数字上有3个1,小伙伴猜的数字有1个1,那么取两者中的小者就是这个数字猜对了不过位置错了的个数。
代码如下:
class Solution {
public:
string getHint(string secret, string guess) {
if(secret.size() != guess.size())return "";
int count_bulls = 0, count_cows = 0;
int count_ori[10];
int count_curr[10];
memset(count_ori, 0, sizeof(count_ori));
memset(count_curr, 0, sizeof(count_curr));
for(int i = 0; i < secret.size(); i++) {
if(secret[i] == guess[i])count_bulls++;
else {
count_ori[secret[i] - '0']++;
count_curr[guess[i] - '0']++;
}
}
for(int i = 0; i < 10; i++) {
count_cows += min(count_ori[i], count_curr[i]);
}
return to_string(count_bulls) + "A" + to_string(count_cows) + "B";
}
};