You is playing the following Bulls and cows game with your friend:you write down a number and ask your friend to guess W Hat the number is. Each time your friend makes a guess, you provide a hint the indicates how many digits in said guess match your secret num ber exactly in both digit and position (called "bulls") and how many digits match the secret number but locate in the Wron G position (called "cows"). Your Friend would use successive guesses and hints to eventually derive the secret number. For Example:secret number:"1807"Friend' s guess: ' 7810 ' hint:1 bull and 3 cows. (The bull is 8, the cows is 0, 1 and 7.) Write a function toreturnA hint according to the secret number and friend's guess, use a to indicate the bulls and B to indicate the cows. In the above example, your function should return "1a3b".Please note that both secret number and friend' s guess may contain duplicate digits, for example: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". Assume that the secret number and your friend's guess only contain digits, and their lengths is always equal.
Good to do, but error-prone, statistics A and statistics B should be separated, priority statistics A and then statistics B, statistics A and also record a position, in the statistics B should be skipped
1 Public classSolution {2 Publicstring Gethint (String secret, String guess) {3StringBuffer res =NewStringBuffer ();4 intBulls=0, Cows=0;5 int[] Summary =New int[10];6Hashset<integer> matched =NewHashset<integer>();7 for(inti=0; I<secret.length (); i++) {8 Charc =Secret.charat (i);9summary[(int) (C-' 0 ')]++;Ten } One for(intk=0; K<guess.length (); k++) { A CharD =Guess.charat (k); - if(d = =Secret.charat (k)) { -bulls++; thesummary[(int) (D-' 0 ')]--; - Matched.add (k); - } - } + for(intk=0; K<guess.length (); k++) { - if(Matched.contains (k))Continue; + CharD =Guess.charat (k); A if(Summary[(int) (D-' 0 ')] > 0) { atcows++; -summary[(int) (D-' 0 ')]--; - } - } - res.append (Bulls); -Res.append (' A '); in res.append (cows); -Res.append (' B '); to returnres.tostring (); + } -}
Leetcode:bulls and cows