Leetcode 299 Solution

This article provides solution to leetcode question 299 (bulls-and-cows)

https://leetcode.com/problems/bulls-and-cows

Solution

class Solution {
public:
    string getHint(string secret, string guess) {
        int m = secret.size();
        int n = guess.size();

        int bull_cnt = 0;

        vector<int> secret_cnts(10);
        vector<int> guess_cnts(10);

        for (int i = 0; i < min(m, n); i++)
        {
            if (secret[i] == guess[i])
                bull_cnt++;
            else
            {
                secret_cnts[secret[i] - '0']++;
                guess_cnts[guess[i] - '0']++;
            }
        }

        for (int i = min(m, n); i < max(m, n); i++)
        {
            if (i < m)
                secret_cnts[secret[i] - '0']++;
            if (i < n)
                guess_cnts[guess[i] - '0']++;
        }

        int cow_cnt = 0;
        for (int i = 0; i < 10; i++)
            cow_cnt += min(secret_cnts[i], guess_cnts[i]);

        return to_string(bull_cnt) + "A" + to_string(cow_cnt) + "B";
    }
};