-
Notifications
You must be signed in to change notification settings - Fork 0
/
bullsAndCows.txt
39 lines (32 loc) · 1.42 KB
/
bullsAndCows.txt
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
299. Bulls and Cows
You are playing the Bulls and Cows game with your friend.
You write down a secret number and ask your friend to guess what the number is.
When your friend makes a guess, you provide a hint with the following info:
The number of "bulls", which are digits in the guess that are in the correct position.
The number of "cows", which are digits in the guess that are in your secret number but are located in the wrong position.
Specifically, the non-bull digits in the guess that could be rearranged such that they become bulls.
Given the secret number secret and your friend's guess guess, return the hint for your friend's guess.
The hint should be formatted as "xAyB", where x is the number of bulls and y is the number of cows.
Note that both secret and guess may contain duplicate digits
class Solution {
public:
string getHint(string& secret, string &guess) {
unordered_map<char,int> secret_freq;
unordered_map<char,int> guess_freq;
int size = secret.size();
int bulls = 0;
int cows = 0;
for(int i = 0; i < size; i++){
if(secret[i] == guess[i]){
bulls++;
}else{
secret_freq[secret[i]]++;
guess_freq[guess[i]]++;
}
}
for(auto it: guess_freq){
cows += min(it.second,secret_freq[it.first]);
}
return to_string(bulls)+"A"+to_string(cows)+"B";
}
};