One Pass 2ms JAVA


  • 0
    Q
    1. maintain a count of each 0-9 digits.
    2. when secret number digits count is negative, meaning guess number digit before has a hit.
    3. when guess number digits count is positive meaning guess digit hit a digit in secret number before.
    4. When hitting bulls, don't need to change count since the count produced by the secret number has been consumed by the guess number right away.
    public class Solution {
        public String getHint(String secret, String guess) {
            int[] nCnt = new int[10];
            int aCnt = 0, bCnt = 0;
            char[] secChar = secret.toCharArray();
            char[] gusChar = guess.toCharArray();
            for (int i = 0; i < secChar.length; ++i) {
                if (secChar[i] == gusChar[i]) {
                    aCnt++; 
                } else {
                    bCnt = (nCnt[secChar[i]-'0'] < 0) ? bCnt+1: bCnt;
                    bCnt = (nCnt[gusChar[i]-'0'] > 0) ? bCnt+1: bCnt;
                    nCnt[secChar[i]-'0']++;
                    nCnt[gusChar[i]-'0']--;
                }
            }
            return ""+aCnt +"A"+bCnt+"B";
        }
    }

Log in to reply
 

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