|
1 | 1 | package com.fishercoder.solutions;
|
2 | 2 |
|
3 |
| -/**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. |
| 3 | +/** |
| 4 | + * 299. Bulls and Cows |
| 5 | + * |
| 6 | + * You are playing the following Bulls and Cows game with your friend: |
| 7 | + * You write down a number and ask your friend to guess what the number is. |
| 8 | + * 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 |
| 9 | + * both digit and position (called "bulls") and how many digits match the secret number but locate in the wrong position (called "cows"). |
| 10 | + * Your friend will use successive guesses and hints to eventually derive the secret number. |
4 | 11 |
|
5 | 12 | For example:
|
6 | 13 |
|
|
16 | 23 | 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".
|
17 | 24 | You may assume that the secret number and your friend's guess only contain digits, and their lengths are always equal.*/
|
18 | 25 | public class _299 {
|
19 |
| - |
20 |
| - public String getHint(String secret, String guess) { |
21 |
| - int[] secretCows = new int[10]; |
22 |
| - int[] guessCows = new int[10]; |
23 |
| - int bulls = 0; |
24 |
| - for (int i = 0; i < secret.length(); i++) { |
25 |
| - if (guess.charAt(i) == secret.charAt(i)) { |
26 |
| - bulls++; |
27 |
| - } else { |
28 |
| - secretCows[Character.getNumericValue(secret.charAt(i))]++; |
29 |
| - guessCows[Character.getNumericValue(guess.charAt(i))]++; |
| 26 | + public static class Solution1 { |
| 27 | + public String getHint(String secret, String guess) { |
| 28 | + int[] secretCows = new int[10]; |
| 29 | + int[] guessCows = new int[10]; |
| 30 | + int bulls = 0; |
| 31 | + for (int i = 0; i < secret.length(); i++) { |
| 32 | + if (guess.charAt(i) == secret.charAt(i)) { |
| 33 | + bulls++; |
| 34 | + } else { |
| 35 | + secretCows[Character.getNumericValue(secret.charAt(i))]++; |
| 36 | + guessCows[Character.getNumericValue(guess.charAt(i))]++; |
| 37 | + } |
30 | 38 | }
|
| 39 | + int cows = 0; |
| 40 | + for (int i = 0; i < 11; i++) { |
| 41 | + cows += Math.min(secretCows[i], guessCows[i]); |
| 42 | + } |
| 43 | + return bulls + "A" + cows + "B"; |
31 | 44 | }
|
32 |
| - int cows = 0; |
33 |
| - for (int i = 0; i < 11; i++) { |
34 |
| - cows += Math.min(secretCows[i], guessCows[i]); |
35 |
| - } |
36 |
| - return bulls + "A" + cows + "B"; |
37 | 45 | }
|
38 |
| - |
39 | 46 | }
|
0 commit comments