LeetCode299BullsandCows

## meaning of a title

You are playing the following bull and cow game with your friend: you write down a number and ask your friend to guess what the number is. Whenever your friend guesses, you provide a hint as to how many of the digits in said guess match your password exactly, including the number and location (called a "bull") and how many digits match the password but are in the wrong location (called a "cow"). Write a function that returns a hint based on a secret number and a friend's guess, for A for bull and B for cow.

Example 1:

```importation: secret = "1807", guess = "7810"

exports: "1A3B"

Description: 1 bull and 3 cows.  Bulls are 8, cows are 0, 1 and 7.```

Example 2:

```importation: secret = "1123", guess = "0111"

exports: "1A1B"

instructions: The 1st 1 in friend's guess is a bull, the 2nd or 3rd 1 is a cow.```

## solution (a math problem)

At first my idea was to get the number of bulls and cows in order, but the cow decision requires O(n^2) time complexity, then I thought, using the number of all matches - the number of bulls is the number of cows, which only requires O(n) time complexity and O(1) space complexity.

```public String getHint(String secret, String guess) {
int[] table = new int[10];

int total = 0;
int bulls = 0;
for (char c :secret.toCharArray()) {
table[c - '0']++;
}

for (int i = 0; i < guess.length(); i++) {
if (secret.charAt(i) == guess.charAt(i)) {
bulls++;
}
if (table[guess.charAt(i) - '0']-- > 0) {
total++;
}
}

return bulls + "A" + (total - bulls)  + "B";
}```

Runtime: 1 ms, faster than 100.00% of Java online submissions for Bulls and Cows.

Recommended>>
1、5 biological evolutioninspired projects to improve AI algorithms
2、Shared cars come to people on their own amazing
3、Whats wrong with China
4、35 billion stolen at every turn Is blockchain security really that compromised
5、In the era of big data dividend seizing the first opportunity and forming core competitiveness determine the development of enterprises and even the industry

已推荐到看一看 和朋友分享想法
最多200字，当前共 发送

已发送

确定
分享你的想法...
取消

确定
最多200字，当前共

发送中