4ms concise c++ solution


  • 5
    L
    class Solution {
    public:
        string getHint(string secret, string guess) {
            vector<int> s(10, 0); // s[i]: number of occurrences of i in secret
            vector<int> g(10, 0); // g[i]: number of occurrences of i in guess
            int A = 0;
            for(int i = 0; i < secret.size(); ++i){
                if(secret[i] == guess[i])
                    ++A;
                s[secret[i] - '0']++;
                g[guess[i] - '0']++;
            }
            int B = -A;
            for(int i = 0; i < 10; ++i){
                B += min(s[i], g[i]);
            }
            return to_string(A) + "A" + to_string(B) + "B";
        }
    };

  • 0
    S

    nice solution! I used to get bulls and cows with O(n2) tc.


Log in to reply
 

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