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.
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.
Please note that both secret number and friend's guess may contain duplicate digits.
Example 1:
Input: secret = "1807", guess = "7810"
Output: "1A3B"
Explanation: 1 bull and 3 cows. The bull is 8, the cows are 0, 1 and 7.
Example 2:
Input: secret = "1123", guess = "0111"
Output: "1A1B"
Explanation: The 1st 1 in friend's guess is a bull, the 2nd or 3rd 1 is a cow.
Note: You may assume that the secret number and your friend's guess only contain digits, and their lengths are always equal.
input:
"1807"
"7810"
"1123"
"0111"
"1110"
"0110"
"1234"
"0111"
output:
"1A3B"
"1A1B"
"3A0B"
"0A1B"
第一次成功的思路:使用一个map来记录cows的数字,还有一个bool数组来记录是否略过遍历。
string getHint(string secret, string guess) {
int cows=0,bull=0,sz=secret.size();
unordered_map <char,int> map;
vector<bool> flag(sz,false);
for(int i=0;i<sz;i++){
if(secret[i]==guess[i]){
bull++;
flag[i]=true;
}
else
map[secret[i]]++;
}
for(int i=0;i<sz;i++){
if(flag[i])
continue;
auto p=map.find(guess[i]);
if(p!=map.end()){
if(map[guess[i]]>0)
cows++;
map[guess[i]]--;
}
}
return to_string(bull)+"A"+to_string(cows)+"B";
}
更好的方法(来自其他人):使用两个数组,分别统计Secret和guess 的数字的数目
string getHint(string secret, string guess) {
int bull=0,cows=0,sz=secret.size();
vector<int> svec(10,0),gvec(10,0);
for(int i=0;i<sz;i++){
char s=secret[i],g=guess[i];
if(s==g)
bull++;
else{
svec[s-'0']++;
gvec[g-'0']++;
}
}
for(int i=0;i<10;i++){
cows+=min(svec[i],gvec[i]);
}
return to_string(bull)+"A"+to_string(cows)+"B";
}
python
def getHint(self, secret: str, guess: str) -> str:
bull,cows=0,0
svec,gvec={},{}
for i in range(len(secret)):
s,g=secret[i],guess[i]
if s==g:
bull+=1
else:
if s in svec:
svec[s]+=1
else:
svec[s]=1
if g in gvec:
gvec[g]+=1
else:
gvec[g]=1
for i in gvec:
if i in svec:
cows+=min(svec[i],gvec[i])
return '%sA%sB' % (bull,cows)
三行:zip
def getHint(self, secret: str, guess: str) -> str:
s, g = Counter(secret), Counter(guess)
a = sum(i == j for i, j in zip(secret, guess))
return '%sA%sB' % (a, sum((s & g).values()) - a)

本文深入解析了 Bulls and Cows 游戏的算法实现,提供了两种高效解决方案,包括使用 map 和 bool 数组的方法,以及利用两个数组统计数字出现次数的优化方案。通过 Python 和 C++ 的代码示例,详细展示了如何计算猜测与秘密数字之间的 bulls 和 cows 数量。
744

被折叠的 条评论
为什么被折叠?



