Storing count of characters in hashmap


  • 0

    '''
    class Solution {
    public String getHint(String secret, String guess) {

        int cows =0;
        int bulls =0;
        HashMap<Character, Integer> chars = new HashMap<Character, Integer>();
        
        for (int i =0 ; i <secret.length(); i++)
        {
            if(secret.charAt(i) == guess.charAt(i))
            {
                bulls ++;
            }
            else
            {
                if (chars.containsKey(secret.charAt(i)))
                    chars.put(secret.charAt(i), chars.get(secret.charAt(i))+1);
                    else
                    chars.put(secret.charAt(i), 1);
            }
        }
        for (int i =0 ; i <secret.length(); i++)
        {
            if(secret.charAt(i) != guess.charAt(i) && chars.containsKey(guess.charAt(i)))
            {
                if (chars.get(guess.charAt(i)) > 0)
                {
                    cows++;
                    chars.put(guess.charAt(i), chars.get(guess.charAt(i))-1);
                }
            }
        }        
        String result = "" + bulls + "A" + cows + "B";
        return result;
    }
    

    }
    '''


  • 0
    C

    '''
    secret.charAt(i) != guess.charAt(i)
    '''
    Rather than using charAt, if one initially converts to a character array and iterating over it is efficient.


Log in to reply
 

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