# 2ms Java solution

• ``````public String getHint(String secret, String guess) {
String result = "";
char[] secretC = secret.toCharArray();
char[] guessC = guess.toCharArray();
int[] hash = new int[20];
int A=0,B=0;
for(int i=0; i<secretC.length; ++i){
if(secretC[i] == guessC[i]){
++A;
}
else{
hash[secretC[i]-48]++;
hash[guessC[i]-48+10]++;
}
}
for(int i=0; i<10; ++i){
if(hash[i] > hash[i+10]){
B += hash[i+10];
}
else{
B += hash[i];
}
}
result = A+"A"+B+"B";
return result;
}
``````

Note: Use ' result ' to save ' A+"A"+B+"B" '(2ms) will faster than direct return A+"A"+B+"B" (3ms)here,and i don't know why...hope someone could help me,thx!~

• First I'm wondering why you use an array with size of 20. Then I figured out.
We share the same Idea, however I use the array with the size of 10:

``````    public String getHint(String secret, String guess) {
char[] s = secret.toCharArray();
char[] g = guess.toCharArray();
int a = 0;
int b = 0;
int[] table = new int[10];

//initial look up table
for(int i = 0; i < secret.length(); i++){
table[s[i]-'0']++;
}

for(int i = 0; i < secret.length(); i++){
//save value and same position, count as bull
if(s[i] == g[i] - '0') a++;
//if share the same value but not the same position, it works as anagrams
if(table[g[i] - '0'] > 0){
b++;//this b counts bulls and cows together
table[g[i] - '0']--;
}
}

return a + "A" + (b-a) + "B";
}
``````

I'm also curious that output a defined String is faster than output a equation. It would be better someone can explain that. Thanks advance.

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.