Help -- cannot get Cow count. What's wrong with my code?


  • 0
    J
    public class Solution {
    public String getHint(String secret, String guess) {
        if (secret == null || guess == null || secret.length() == 0 || guess.length() == 0) {
            return "";
        }
        int countA = 0;
        int countB = 0;
        int total = 0;
        
        HashMap<Character, Integer> map = new HashMap<Character, Integer>();
        for (int i = 0;i < secret.length();i++) {
            if (map.containsKey(secret.charAt(i))) {
            map.put(secret.charAt(i), map.get(secret.charAt(i))+1);
            }
            map.put(secret.charAt(i), 1);
        }
        
        for (int i = 0;i < guess.length(); i++) {
            char g = guess.charAt(i);
            char s = secret.charAt(i);
             if (s == g) {
                 total++;
            }else {
                  if (map.containsKey(g)) {
                      int count = map.get(g);
                      if (count > 0) {
                          total++;
                         map.put(g, count--);
                      }
                }
            }
        }
        for (int i = 0;i < guess.length(); i++) {
            char s = secret.charAt(i);
            char cur = guess.charAt(i);
            if (s == cur) {
                countA++;
            }
        }
        countB = total - countA;
        
        return String.format("%dA%dB", countA, countB);
    }
    

    }


  • 0
    T

    You're missing an else when building the map:

        if (map.containsKey(secret.charAt(i))) {
            map.put(secret.charAt(i), map.get(secret.charAt(i))+1);
        }
        map.put(secret.charAt(i), 1); // overwrite value, even if it was incremented
    

    VS

        if (map.containsKey(secret.charAt(i))) {
            map.put(secret.charAt(i), map.get(secret.charAt(i))+1);
        } else {
            map.put(secret.charAt(i), 1);
        }
    

    or (slower, but without else)

        if (!map.containsKey(secret.charAt(i))) { // notice the not operator
            map.put(secret.charAt(i), 0);            
        }
        map.put(secret.charAt(i), map.get(secret.charAt(i))+1);

Log in to reply
 

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