Java solution beast 25%


  • 0
    V
        public String getHint(String secret, String guess) {
            Hashtable<Integer, Integer> hash = new Hashtable<Integer,Integer>();
            int n1 = secret.length();
            int n2 = guess.length();
            int cows = 0, bulls = 0;
            boolean[] done = new boolean[n2];
    
            for(int i = 0; i < n1; i++ ) {
                int current = Character.getNumericValue(secret.charAt(i));
                if( i < n2 && secret.charAt(i) == guess.charAt(i) ) {
                    bulls++;
                    done[i] = true;
                }
                else {
                    if(hash.get(current) != null)
                        hash.put(current, hash.get(current)+1);
                    else
                        hash.put(current, 1);
                }
            }
            for(int j = 0; j < n2; j++) {
                int cur = Character.getNumericValue(guess.charAt(j));
                if(!done[j] && hash.get(cur) != null && hash.get(cur) != 0) {
                    cows++;
                    hash.put(cur,hash.get(cur)-1);
                }
            }
            return bulls+"A"+cows+"B";
        }
    

Log in to reply
 

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