https://leetcode.com/problems/bulls-and-cows/
Examples:
Secret: 1807 Secret: 1123
Guess: 7810 ====> "0A3B" Guess: 0111 ====> "1A1B"
Secret: 1122 Secret: 121
Guess: 1222 ====> "3A0B" Guess: 222 ====> "1A0B"
So getting the bull number is easy by just counting the number of matched pairs. The problem is to count the number of cows(mismatches).
1)Mismatched element from guess string has to be existed in secret string.
2)The # of mimatched occurence of that element in guess = # of mimatched occurence of that element in secret ;
3)We keep track of each mismatched pair by increasing the number by 1 for secret string and decreasing the number by 1 for guess string
4)If count[guess]>0,then that means this element has occured in secret string and it was a mismactch, thus,we can increase the cow since this element is now found in the guess string;
5)If count[secret]<0,then that means this element has occured in guess string and it was a mismactch, thus,we can increase the cow since this element is now found in the secret string;
public String getHint(String secret, String guess) { if((secret==null||secret.length()==0)||(guess==null||guess.length()==0)){ return "0A0B"; } int match=0; int mismatch=0; int[] count=new int[10]; for(int i=0;i<secret.length();i++){ char s=secret.charAt(i); char g=guess.charAt(i); if(s==g){ match++; }else{ if(count[s-‘0‘]<0){ mismatch++; } if(count[g-‘0‘]>0){ mismatch++; } count[g-‘0‘]--; count[s-‘0‘]++; } } return match+"A"+mismatch+"B"; }