Java solution using hashmap with explanation

  • 0
    public class Solution {
        public String getHint(String secret, String guess) {
            HashMap<Character,Integer> hm = new HashMap<>();
            int bull = 0;
            int cow = 0;
            // list to store the characters in 'guess' that 
            // do not match the characters in the corresponding positin in 'secret'
            List<Character> mismatch = new ArrayList<>();
            for(int i = 0; i < secret.length();i++){
                char si = secret.charAt(i);
                char gi = guess.charAt(i);
                if(si == gi) bull++;
                // if not equal, store the character from 'secret' to hashmap
                    if(!hm.containsKey(si)) hm.put(si,0);
                    hm.put(si,hm.get(si)+1);// in hashmap, this automatically overwrite the original pair
                // store the character from 'guess' to list
            for(int i = 0; i < mismatch.size(); i++){
                char temp = mismatch.get(i);
                // if this character from 'guess' shows in 'secret', cow+1
                    // the values in the map record how many times the key shows up
                    // if the key only shows once, after this checking,
                    // remove it to avoid double counting
                    if(hm.get(temp) == 1) hm.remove(temp);
                    // if shows many times, reduce by one
                    else hm.put(temp, hm.get(temp)-1);
            return String.valueOf(bull)+"A"+String.valueOf(cow)+"B";

Log in to reply

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