Short C++, O(n)


  • 0

    Just a dense implementation of the algorithm I saw from others.

    string getHint(string secret, string guess) {
        int a = 0, b = 0, c[99] = {}, i = 0;
        for (char s : secret) {
            char g = guess[i++];
            a += s == g;
            b += (c[s]++ < 0) + (c[g]-- > 0);
        }
        return to_string(a) + "A" + to_string(b - a) + "B";
    }
    

    Or:

    string getHint(string secret, string guess) {
        int a = 0, b = 0, c[99] = {}, i = 0, g;
        for (int s : secret) {
            a += s == (g = guess[i++]);
            b += (c[s]++ < 0) + (c[g]-- > 0);
        }
        return to_string(a) + "A" + to_string(b - a) + "B";
    }

Log in to reply
 

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