Why my solution does not work?


  • 0
    B
    public String getHint(String secret, String guess) {
            if (secret.length() != guess.length()) return "";
            char[] counter = new char[10];
            int bulls = 0;
            int cows = 0;
            for(int i = 0; i < guess.length(); i++){
                char c_s = secret.charAt(i);
                char c_g = guess.charAt(i);
                if (c_s == c_g) bulls++;
                else{
                    if (counter[c_s - '0']++ < 0) cows++;
                    if (counter[c_g - '0']-- > 0) cows++;
                }
            }
            return bulls + "A" + cows + "B";
        }
    

    test case 12,21 gives 0A1B rather than 0A2B, but I dont know why...Could anyone tell me?


  • 4

    Because you use char[] for your counter and Java doesn't have signed chars, so the counts never get negative.


Log in to reply
 

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