Topic:
You is playing the following Bulls and cows game with your friend:you write down a number and ask your friend T O guess what, the number is. Each time your friend makes a guess, you provide a hint the indicates how many digits in said guess match your secret num ber exactly in both digit and position (called "bulls") and how many digits match the secret number but locate in the Wron G position (called "cows"). Your Friend would 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. ( 8
the bull is, the cows 0
is, and 1
7
.)
Write a function to return a hint according to the secret number and friend's guess, use to A
indicate the Bulls and c1/> 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 .
Assume that the secret number and your friend's guess only contain digits, and their lengths is always equal.
Topic answer: This topic in the implementation of time, the code is more complex to write. First, you need to count the number of letters that both share. Two map structures are used. The number that should be B does not include a, and it is also necessary to subtract the number of pairs in the position of the pair.
The code is as follows:
Class Solution {
Public
String Gethint (String secret, String guess) {
Map<char,int> B_map;
Map<char,int> B_MAP2;
int a_count = 0;
int b_count = 0;
int len = Secret.length ();
if ((Secret = = "") | | (Guess = = "") | | (Secret.length ()! = Guess.length ()))
Return "";
for (int i = 0;i < len;i++)
{
if (B_map.find (secret[i]) = = B_map.end ())
B_map[secret[i]] = 1;
Else
b_map[secret[i]]++;
}
for (int i = 0;i < len;i++)
{
if (secret[i] = = Guess[i])
{
a_count++;
b_map[secret[i]]--;
}
Else
{
if (B_map2.find (guess[i]) = = B_map2.end ())
B_map2[guess[i]] = 1;
Else
b_map2[guess[i]]++;
}
}
Map<char,int>::iterator mit = B_map.begin ();
while (mit! = B_map.end ())
{
If (MIT-second > 0)
{
if (B_map2.find (MIT-first)! = B_map2.end ())
{
int tmp =min (MIT-Second, B_map2[mit-first]);
B_count + = tmp;
}
}
mit++;
}
StringStream Res;
Res.clear ();
Res << a_count << ' A ' << b_count << ' B ';
return Res.str ();
}
int min (int a, int b)
{
Return a < b? A:B;
}
};
Leetcode title: Bulls and Cows