Physical Address
304 North Cardinal St.
Dorchester Center, MA 02124
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:
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.
Example 1:
Input: secret = "1807", guess = "7810"
Output: "1A3B"
Explanation: Bulls are connected with a '|' and cows are underlined:
"1807"
|
"7810"
Example 2:
Input: secret = "1123", guess = "0111"
Output: "1A1B"
Explanation: Bulls are connected with a '|' and cows are underlined:
"1123" "1123"
| or |
"0111" "0111"
Note that only one of the two unmatched 1s is counted as a cow since the non-bull digits can only be rearranged to allow one 1 to be a bull.
Constraints:
1 <= secret.length, guess.length <= 1000
secret.length == guess.length
secret
and guess
consist of digits only.public String getHint(String secret, String guess) {
int bulls = 0;
int cows = 0;
int[] numbers = new int[10];
for (int i = 0; i<secret.length(); i++) {
if (secret.charAt(i) == guess.charAt(i)) bulls++;
else {
if (numbers[secret.charAt(i)-'0']++ < 0) cows++;
if (numbers[guess.charAt(i)-'0']-- > 0) cows++;
}
}
return bulls + "A" + cows + "B";
}
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';
}
};
s, g = Counter(secret), Counter(guess)
a = sum(i == j for i, j in zip(secret, guess))
return '%sA%sB' % (a, sum((s & g).values()) - a)
In our experience, we suggest you solve this Bulls and Cows LeetCode Solution and gain some new skills from Professionals completely free and we assure you will be worth it.
If you are stuck anywhere between any coding problem, just visit Queslers to get the Bulls and Cows LeetCode Solution
I hope this Bulls and Cows LeetCode Solution would be useful for you to learn something new from this problem. If it helped you then don’t forget to bookmark our site for more Coding Solutions.
This Problem is intended for audiences of all experiences who are interested in learning about Data Science in a business context; there are no prerequisites.
Keep Learning!
More Coding Solutions >>