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 was 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 have to is existed in secret string.
2) The # of mimatched occurence of that element in guess = # of mimatched occurence of the. element in secret;
3) We keep track's 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 have occured in secret string and it is a mismactch, Thus,we can incr Ease the cow since this element was now found in the Guess string;
5) If count[secret]<0,then That means this element have occured in guess string and it is a mismactch, Thus,we can incr Ease the cow since this element was now found in the secret string;
Publicstring Gethint (String secret, String guess) {if((secret==NULL|| Secret.length () ==0) | | (guess==NULL|| Guess.length () ==0)){ return"0A0B"; } intMatch=0; intMismatch=0; int[] count=New int[10]; for(intI=0;i<secret.length (); i++){ Chars=Secret.charat (i); Charg=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 ']++; } } returnmatch+ "A" +mismatch+ "B"; }
Lc-bulls and cows