Bulls and Cows
ID
299
Data Type
Hashmap / Hashset
Difficulty
Medium
Tags
Completed Date
May 14, 2024
Preference
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.Example 1:
Example 2:
Constraints:
1 <= secret.length, guess.length <= 1000
secret.length == guess.length
secret
andguess
consist of digits only.
题解
这个题比较简单,逐位找,如果一样就A++,不一样要记录下,我一开始想的是只记录一个,结果发现不知道最后有几个数,只能检测全部是不同位的,如果有同位就检测不到了,例如
0011
和 1100