leetcode 299 bulls and cows

You are playing the following Bulls and Cows game with your friend: You write down a number and ask your friend to guess what the number is. Each time your friend makes a guess, you provide a hint that indicates how many digits in said guess match your secret number exactly in both digit and position (called “bulls”) and how many digits match the secret number but locate in the wrong position (called “cows”). Your friend will use successive guesses and hints to eventually derive the secret number.

For example:

1
2
Secret number:  "1807"
Friend's guess: "7810"

Hint: 1 bull and 3 cows. (The bull is 8, the cows are 0, 1 and 7.)

Please note that both secret number and friend’s guess may contain duplicate digits, for example:

1
2
Secret number:  "1123"
Friend's guess: "0111"

In this case, the 1st 1 in friend’s guess is a bull, the 2nd or 3rd 1 is a cow, and your function should return "1A1B".

You may assume that the secret number and your friend’s guess only contain digits, and their lengths are always equal.


  • 对于bull,是很好统计的。对应位置的数字相同,bull++即可

  • 但是对于cows,统计起来需要技巧。

    • 1
      2
      3
      4
      secret	: 10
      guess : 01
      bull : 0
      cows : 2
      1
      2
      3
      4
      secret	: 100
      guess : 010
      bull : 1
      cows : 2
      1
      2
      3
      4
      secret	: 11
      guess : 01
      bull : 1
      cows : 0
      1
      2
      3
      4
      secret	: 01
      guess : 11
      bull : 1
      cows : 0

      对于每一个guess[i]!=secret[i]的元素

      ​ 如果guess中元素,在secret中存在且没有与secret中配对的guess中的元素,则cows++

      ​ 如果secret中元素,在guess中存在且没有与guess中配对的guess中的元素,则cow++


    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    class Solution{
    public String getHint(String secret, String guess){
    int bull = 0;
    int cows = 0;
    int[] helper = new int[10];
    for(int i=0; i<secret.length(); i++){
    int m = secret.charAt(i) - '0';
    int n = guess.charAt(i) - '0';
    if(m == n){
    bull ++;
    }
    else{
    if(helper[m] < 0) cows ++;
    if(helper[n] > 0) cows ++;
    helper[m] ++;
    helper[n] --;
    }
    return bull + "A" + cows + "B";
    }
    }