My Concise JAVA Solution


  • 8
    J
    public String getHint(String secret, String guess) {
        int a=0,b=0;
        int[] digits=new int[10];
        for(int i=0;i<secret.length();i++){
            if(secret.charAt(i)==guess.charAt(i)) a++;
            else{
                if(++digits[secret.charAt(i)-'0']<=0) b++;
                if(--digits[guess.charAt(i)-'0']>=0) b++;
            }
        }
        return a+"A"+b+"B";
    }

  • 0
    R

    i just don't understand the meaning of
    if(++digits[secret.charAt(i)-'0']<=0) b++;
    if(--digits[guess.charAt(i)-'0']>=0) b++;


  • 0
    J

    int b is the count of 'cow' events. The int[] digits stores the frequency of each digit (from 0 to 9) in secret and guess.
    ++digits[n] means digit n is found in secret. If digits[n] was 0, now it becomes 1 denoting that n has shown up once in secret,
    while --digits[n] means n is found in guess.
    Digits[n] being smaller than 0 means n has shown up in guess before. Therefore when we find n in secret and do ++digits[n], having ++digits[n]<=0 means n was somewhere in the guess before. It is confirmed a 'cow'.
    Vice versa, --digits[n] >=0 means n is found in guess AND n has shown up in secret before, which makes a 'cow'.


Log in to reply
 

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