One Pass JAVA 2 ms beats 95%


  • 0
    M

    Have added relevant comments.

    public static String getHint(String secret, String guess) {
    		int[] cnt = new int[10]; //Count the digits in secret
    		for (char c : secret.toCharArray()){
    			cnt[c - '0']++;
    		}
    		int j = 0, bulls = 0, cows = 0;
    		for (char c : guess.toCharArray()){
    			int ind = c - '0';
    			if (secret.charAt(j) == c){
    				bulls++;
    				cnt[ind]--;
                                //if cnt <0 we double counted cows so decrement by 1
    				if (cnt[ind] < 0)  cows--; 
    			} else if (cnt[ind] > 0) {
    				cows++;
    				cnt[ind]--;
    			}
    			j++;
    		}
    		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.