你正在和你的朋友玩 猜数字(Bulls and Cows)游戏:你写下一个数字让你的朋友猜。每次他猜测后,你给他一个提示,告诉他有多少位数字和确切位置都猜对了(称为“Bulls”, 公牛),有多少位数字猜对了但是位置不对(称为“Cows”, 奶牛)。你的朋友将会根据提示继续猜,直到猜出秘密数字。
请写出一个根据秘密数字和朋友的猜测数返回提示的函数,用 A
表示公牛,用 B
表示奶牛。
请注意秘密数字和朋友的猜测数都可能含有重复数字。
示例 1:
输入: secret = "1807", guess = "7810"
输出: "1A3B"
解释: 1 公牛和 3 奶牛。公牛是 8,奶牛是 0, 1 和 7。
示例 2:
输入: secret = "1123", guess = "0111"
输出: "1A1B"
解释: 朋友猜测数中的第一个 1是公牛,第二个或第三个1可被视为奶牛。
说明: 你可以假设秘密数字和朋友的猜测数都只包含数字,并且它们的长度永远相等。
C
char * getHint(char * secret, char * guess)
{
int pos=0;
int neg=0;
int i=0;
int* tmp1=(int*)malloc(sizeof(int)*10);
int* tmp2=(int*)malloc(sizeof(int)*10);
memset(tmp1,0,sizeof(int)*10);
memset(tmp2,0,sizeof(int)*10);
while(secret[i]!='\0')
{
if(secret[i]==guess[i])
{
pos++;
}
else
{
tmp1[secret[i]-'0']++;
tmp2[guess[i]-'0']++;
}
i++;
}
for(int k=0;k<10;k++)
{
int tmp=tmp1[k]<tmp2[k]?tmp1[k]:tmp2[k];
neg+=tmp;
}
char aa[1000];
char* res=(char*)malloc(sizeof(char)*1000);
sprintf(aa,"%d",pos);
int t=0;
while(aa[t]!='\0')
{
res[t++]=aa[t];
}
res[t++]='A';
sprintf(aa,"%d",neg);
int s=0;
while(aa[s]!='\0')
{
res[t++]=aa[s++];
}
res[t++]='B';
res[t]='\0';
return res;
}
C++
class Solution {
public:
string getHint(string secret, string guess)
{
map<int,int> tmp1;
map<int,int> tmp2;
int pos=0;
int n=secret.size();
for(int i=0;i<n;i++)
{
if(secret[i]==guess[i])
{
pos++;
}
else
{
tmp1[secret[i]]++;
tmp2[guess[i]]++;
}
}
int neg=0;
for(auto it:tmp1)
{
neg+=min(it.second,tmp2[it.first]);
}
string res=to_string(pos)+'A'+to_string(neg)+'B';
return res;
}
};
python
class Solution:
def getHint(self, secret: str, guess: str) -> str:
n=len(secret)
dic1={}
dic2={}
pos=0
neg=0
for i in range(n):
if secret[i]==guess[i]:
pos+=1
else:
if secret[i] in dic1:
dic1[secret[i]]+=1
else:
dic1[secret[i]]=1
if guess[i] in dic2:
dic2[guess[i]]+=1
else:
dic2[guess[i]]=1
for key in dic1:
if key in dic2:
neg+=min(dic1[key],dic2[key])
res=str(pos)+'A'+str(neg)+'B'
return res