-
Notifications
You must be signed in to change notification settings - Fork 92
/
Copy pathBulls&Cows.cpp
37 lines (30 loc) · 1.4 KB
/
Bulls&Cows.cpp
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
//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.
class Solution {
public:
// only contains digits
string getHint(string secret, string guess) {
int aCnt = 0;
int bCnt = 0;
vector<int> sVec(10, 0); // 0 ~ 9 for secret
vector<int> gVec(10, 0); // 0 ~ 9 for guess
if (secret.size() != guess.size() || secret.empty()) { return "0A0B"; }
for (int i = 0; i < secret.size(); ++i) {
char c1 = secret[i]; char c2 = guess[i];
if (c1 == c2) {
++aCnt;
} else {
++sVec[c1-'0'];
++gVec[c2-'0'];
}
}
// count b
for (int i = 0; i < sVec.size(); ++i) {
bCnt += min(sVec[i], gVec[i]);
}
return to_string(aCnt) + 'A' + to_string(bCnt) + 'B';
}
};