Simple & Easy Understand CPP


  • 2
    S
    class Solution {
    public:
        string getHint(string secret, string guess) {
            
            int n = secret.size();
            int p[10] = {0}; //record how many times chars in Secret guessed by Guess
            int A = 0;
            for (int i = 0; i < n; i++) {
                p[secret[i] - '0'] ++; //Appeared
                p[guess[i] - '0'] --; //Guessed
                
                if (secret[i] == guess[i]) A++; //Matched
            }
            
            int left = 0; //Elements in P that > 0 are those in Secret but not fully guessed by Guess
            for (int i = 0; i < 10; i++) {
                left += (p[i] > 0) ?p[i] :0;
            }
            //A is cow, n-left is guessed right, n-left-A is bull
            ostringstream oss;
            oss << A << "A" << n - left - A << "B";
            return oss.str();
        }
    };

  • 0
    L

    that's very brilliant! thank you for writing such an answer, it's a subtle method that one can't hardly come up with.


Log in to reply
 

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