b = all - a HashMap One Pass Java Solution with explanation


  • 0
    E

    I use Stan's B = all - A brilliant idea. Build the HashMap <Character, Integer> with Characters and its frequency as the Integer.
    Calculation are done in one pass. Takes 15ms

    Calculate All: secret = "1233", guess = "1122"

    1. Build the map, which is
      '1'-> 1,
      '2' -> 1,
      '3' -> 2
    2. Traverse all chars in guess, Calculate bulls. Increment of As and alls are totally independent from each other
    3. Calculate all: For chars in guess, f secret has it (map contains it), frequency will be reduced one, and all++

    So, after calculation, the map has only one element '3' -> 2 and all = 2

    public static String getHintByMaps(String secret, String guess) {
            HashMap<Character, Integer> map = new HashMap<>();
            for (char c : secret.toCharArray()) { //build the map 
                map.put(c, map.containsKey(c) ? map.get(c) + 1 : 1);
            }
    
            int A = 0, all = 0; //number of bulls and total number of both-side existing chars
            for (int i = 0; i < guess.length(); i++) {
                Character c = guess.charAt(i);
                //Increment of bulls
                if (c == secret.charAt(i)) { //Attention: char to Character
                    A++;
                }
                //Calculate  ALL
                if (map.containsKey(c)) {
                    all++;
                    if (map.get(c) - 1 == 0) map.remove(c);
                    else map.put(c, map.get(c) - 1);
                }
            }
            return A + "A" + (all - A) + "B";
        }
    

Log in to reply
 

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