Java solution using HashMap with comment


  • 0
    A
    public String getHint(String secret, String guess) {
        int bulls = 0, cows = 0;
        //This is for recording the occurring time of each number in secret number
        HashMap<Character, Integer> check = new HashMap<Character, Integer>();
        //This is for storing which numbers in guess number are left after getting rid of bulls
        char[] guessA = guess.toCharArray();
        //Initialized the HashMap
        for(Integer i = 0; i < secret.length(); i++){
            if(check.containsKey(secret.charAt(i))) check.put(secret.charAt(i), check.get(secret.charAt(i))+1);
            else check.put(secret.charAt(i),1);
        }
        //First, every time we find a bull, reducing its occurring time once in HashMap and change the bull in guess number to 'A'
        for(Integer i = 0; i < secret.length(); i++){
            if(secret.charAt(i) == guess.charAt(i)){
                bulls++;
                check.put(secret.charAt(i), check.get(secret.charAt(i))-1);
                guessA[i] = 'A';
            }
        }
        //Next, check the cows. According to array guessA, if any number in guessA is contained in HashMap and occurring time is not zero, cows automatically add one and reducing the occurring time once;
        for(Integer i = 0; i < guessA.length; i++){
            if(check.containsKey(guessA[i]) && check.get(guessA[i]) != 0){
                cows++;
                check.put(guessA[i], check.get(guessA[i])-1);
            }
        }
        //This way is more efficient than bulls + "A" + cows + "B" since the latter way have intermediate objects that are created behind the scene;
        return String.valueOf(bulls) + "A" + String.valueOf(cows) + "B";
    }

  • 0
    H
    This post is deleted!

Log in to reply
 

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