g0201_0300.s0299_bulls_and_cows.Solution Maven / Gradle / Ivy
Go to download
Show more of this group Show more artifacts with this name
Show all versions of leetcode-in-java17 Show documentation
Show all versions of leetcode-in-java17 Show documentation
Java Solution for LeetCode algorithm problems, continually updating
package g0201_0300.s0299_bulls_and_cows;
// #Medium #String #Hash_Table #Counting
public class Solution {
public String getHint(String secret, String guess) {
final int[] ans = new int[10];
int bulls = 0;
int cows = 0;
for (int i = 0; i < secret.length(); i++) {
final int s = Character.getNumericValue(secret.charAt(i));
final int g = Character.getNumericValue(guess.charAt(i));
if (s == g) {
bulls++;
} else {
// digit s was already seen in guess, is being seen again in secret
if (ans[s] < 0) {
cows++;
}
// digit was already seen in secret, now being seen again in guess
if (ans[g] > 0) {
cows++;
}
ans[s]++;
ans[g]--;
}
}
return bulls + "A" + cows + "B";
}
}