翻译
你在和朋友们玩一个叫做“公牛和母牛”的游戏:你写下一组数字,然后让你的朋友来猜它。每次你朋友做一个猜测,你根据他的猜测给一个提示:他在数字在值和位置上都猜对的数字,就叫做bulls(公牛),猜对了值但位置不对的数字叫做cows(母牛)。你的朋友将使用各种猜测和提示最终猜出来正确的数字。
例如:
你给的秘密数字是:“1807”
朋友的猜测是:“7810”
提示:1个公牛和3个母牛。(公牛是8,母牛是0、1、7。)
写一个函数用于根据你给的秘密数字和朋友的猜测做一个提示,使用A来表示公牛,使用B来表示母牛。在上面的例子中,你应该返回但是“1A3B”。
请注意,你给的秘密数字和朋友猜测的数字都可能包含重复的数字,例如:
你给的秘密数字是:“1123”
朋友的猜测是:“0111”
在这个情况下,朋友猜测的第一个1是公牛,第二个和第三个1是母牛,那么你的函数应该返回“1A1B”。
你可以假设秘密数字和猜测数字都只包含数字,并且它们的长度是相等的。
原文
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.
分析
需要注意的是上面的第二个例子,秘密数字是1123,猜测数字是0111,结果是1A1B,而不是1A2B,也就是说后面两个猜错位置但值正确的也只能算一个母牛。
也就是说,如果秘密数字是3456,猜测数字是2333,结果也应该是0A1B,而不是0A3B。
知道规则其实就很容易了,直接看代码吧,当然也可以先看看这些类似的问题~
LeetCode 205 Isomorphic Strings(同构的字符串)(string、vector、map)(*)
LeetCode 290 Word Pattern(单词模式)(istringstream、vector、map)(*)
public String getHint(String secret, String guess) {
int bulls = 0, cows = 0;
int[] s = new int[10], g = new int[10];
for (int i = 0; i < secret.length(); i++) {
char c1 = secret.charAt(i), c2 = guess.charAt(i);
if (c1 == c2) {
bulls++;
} else {
s[c1 - '0']++;
g[c2 - '0']++;
}
}
for (int i = 0; i < s.length; i++) {
cows += Math.min(s[i], g[i]);
}
return bulls + "A" + cows + "B";
}