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.
中文:假设你正在玩猜数字游戏(Bulls and Cows):你写出4个数字让你的朋友猜,每次你的朋友猜一个数字,你给出一条线索,这个线索告诉你的朋友,有多少个数字位置是正确的(被称为Bulls),有多少个数字位置是不正确的(被称为Cows),你的朋友需要根据这些线索最终猜出正确的数字。
class Solution {
public:
string getHint(string secret, string guess) {
if(secret.length() == 0 || guess.length() == 0)
return "0A0B";
int aNum = 0;
int bNum = 0;
int counts[10]; //定义数组存放0~9,这样只需遍历一遍字符串
for(int i = 0;i<10;i++){
counts[i] = 0;
}
for(int i=0; i< secret.length();i++){
if(secret[i] == guess[i]){
aNum++;
}else{
counts[secret[i] - '0']++;
if(counts[secret[i] - '0']<=0){
bNum++;
}
counts[guess[i] - '0']--;
if(counts[guess[i] - '0']>=0){
bNum++;
}
}
}
return to_string(aNum)+"A"+to_string(bNum)+"B"; //to_string()转换字符串
}
};