299. Bulls and Cows
Input: secret = "1807", guess = "7810"
Output: "1A3B"
Explanation: 1 bull and 3 cows. The bull is 8, the cows are 0, 1 and 7.Input: secret = "1123", guess = "0111"
Output: "1A1B"
Explanation: The 1st 1 in friend's guess is a bull, the 2nd or 3rd 1 is a cow.// Two Pass Method
string getHint(string secret, string guess) { // time: O(n); space: O(1)
vector<int> record(10, 0);
int n = secret.length(), bulls = 0, cows = 0;
for (int i = 0; i < n; ++i) {
if (secret[i] == guess[i]) ++bulls;
else ++record[secret[i] - '0'];
}
for (int i = 0; i < n; ++i) {
if (secret[i] != guess[i] && record[guess[i] - '0'] > 0) {
++cows;
--record[guess[i] - '0'];
}
}
return to_string(bulls) + "A" + to_string(cows) + "B";
}Last updated