Java solution with hash table


  • 1
    Y

    1.new hash table for store the times of the secret character.
    2.loop the guess string for finding the bulls and cows.

    public String getHint(String secret, String guess) {
        int bulls = 0;
        int cows = 0;
        Hashtable<Character, Integer> ht = new Hashtable<Character, Integer>();
        for (int i = 0; i < secret.length(); i++) {
        	if (ht.containsKey(secret.charAt(i))) {
        		ht.put(secret.charAt(i), ht.get(secret.charAt(i))+1);
        	} else {
        		ht.put(secret.charAt(i), 1);
        	}
        }
        
        for (int i = 0; i < guess.length(); i++) {
        	if (secret.charAt(i) == guess.charAt(i)) {
        		bulls++;
        	}
        	
        	if (ht.containsKey(guess.charAt(i))) {
        		cows++;
        		if (ht.get(guess.charAt(i)) > 1) {
        			ht.put(guess.charAt(i), ht.get(guess.charAt(i))-1);
        		} else {
        			ht.remove(guess.charAt(i));
        		}
        	}
        }
        
        cows -= bulls;
        
        return new String(bulls+"A"+cows+"B");        
    }

Log in to reply
 

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