您的位置:首页 > 其它

LeetCode 299:Bulls and Cows

2015-12-20 23:14 525 查看
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.
你和你的朋友正在玩一个猜数字游戏:你写下一个数字并让你的朋友来猜。你的朋友每猜一次,你就告诉他有多少个数字猜中并且正好在正确的位置上(称为 bulls ),有多少个数字猜中但不在正确的位置上(称为 cows )。你的朋友将根据每一次猜的结果来最终推测出你写的数字。
例如

秘密数字:  "1807"
朋友猜测:  "7810"

那么应当返回1 bulls 3 cows(数字"8"在正确的位置上,称为bulls;而数字1 7 0不在正确的位置上,称为cows)

编写一个函数来返回你的提示:用A来代表bulls,B代表cows。对于上面那个例子,你的函数应当返回"1A3B"(字符串)。

注意,你的秘密数字和朋友的猜测都可能包含重复的数字,比如:

秘密数字:  "1123"
朋友猜测:  "0111"

在这个案例中,第一个 1 应当为bulls,而第二个第三个1应当为cows,你的函数应该返回"1A1B"。

你可以假定秘密数字和朋友的猜测都只包含数字,并且长度总是相等。

bulls比较好判断,只需要判断相同位置上的数字是否相等;而cows则比较难判断一点,不仅要搜索secret number中是否存在相应数字,即使找到了,也还要看对应数位的friend's guess是否也相同。如果是,那么该位置的数字就是bulls而不是cows。

举个例子

秘密数字:  “011”

朋友猜测:  ”110"

对于第一个1显然是cows,但与他对应的数字应该是秘密数字的最后一个1,而不是第二个1;因为第二个1是bulls。

class Solution {
public:
string getHint(string secret, string guess) {
int bull=0,cows=0;
vector<int> vec;
for(int i=0;i<secret.length();i++)
vec.push_back(secret[i]-'0');
for(int i=0;i<guess.length();i++)
{
if(vec[i]==guess[i]-'0')
{
vec[i]=-1;
bull++;
}
else
{
for(int j=0;j<vec.size();j++)
{
if(vec[j]==-1||guess[j]-'0'==vec[j]) continue;
else if(vec[j]==guess[i]-'0')
{
vec[j]=-1;
cows++;
break;
}
}
}
}
string ans;
char a[10],b[10];
sprintf(a,"%d",bull);
sprintf(b,"%d",cows);
string temp1=a,temp2=b;
ans=temp1+"A"+temp2+"B";
return ans;
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: