11// Source : https://leetcode.com/problems/bulls-and-cows/
2- // Author : Calinescu Valentin
2+ // Author : Calinescu Valentin, Hao Chen
33// Date : 2015-11-04
44
55/* **************************************************************************************
3636
3737class Solution {
3838public:
39- int appears_in_secret[10 ], appears_in_guess[10 ], bulls[10 ];
40- int total_bulls, total_cows;
4139 string getHint (string secret, string guess) {
40+ return getHint02 (secret, guess);
41+ return getHint01 (secret, guess);
42+ }
43+
44+ string getHint01 (string secret, string guess) {
45+ int appears_in_secret[10 ], appears_in_guess[10 ], bulls[10 ];
46+ int total_bulls, total_cows;
4247 for (int i = 0 ; i < secret.size (); i++)
4348 appears_in_secret[secret[i] - ' 0' ]++;
4449 for (int i = 0 ; i < guess.size (); i++)
@@ -54,4 +59,32 @@ class Solution {
5459 }
5560 return to_string (total_bulls) + " A" + to_string (total_cows) + " B" ;
5661 }
62+
63+ // Another implemntation - to save more space
64+ string getHint02 (string secret, string guess) {
65+
66+ const int digital_num = 10 ;
67+ int secret_stat[digital_num]={0 };
68+
69+ int bull = 0 ;
70+ for (int i=0 ; i<secret.size (); i++) {
71+ // both number & location are matched, count bull
72+ if ( secret[i] == guess[i] ) {
73+ bull++;
74+ continue ;
75+ }
76+ // otherwise, count the unmatched digits.
77+ secret_stat[secret[i]-' 0' ]++;
78+ }
79+
80+ int cow = 0 ;
81+ for (int i=0 ; i<guess.size (); i++) {
82+ // deal with duplication - decrease the digits count if cow is found.
83+ if ( secret[i] != guess[i] && secret_stat[guess[i]-' 0' ]-- > 0 ) {
84+ cow++;
85+ }
86+ }
87+
88+ return to_string (bull) + " A" + to_string (cow) + " B" ;
89+ }
5790};
0 commit comments