All Downloads are FREE. Search and download functionalities are using the official Maven repository.

g0201_0300.s0299_bulls_and_cows.Solution Maven / Gradle / Ivy

There is a newer version: 1.24
Show newest version
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";
    }
}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy