LeetCode.299.Bulls and Cows

 

英文:You are playing the following Bulls and Cows game with your friend: You write a 4-digit secret number and ask your friend to guess it, each time your friend guesses a number, you give a hint, the hint tells your friend how many digits are in the correct positions (called "bulls") and how many digits are in the wrong positions (called "cows"), your friend will use those hints to find out the secret number.

中文:假设你正在玩猜数字游戏(Bulls and Cows):你写出4个数字让你的朋友猜,每次你的朋友猜一个数字,你给出一条线索,这个线索告诉你的朋友,有多少个数字位置是正确的(被称为Bulls),有多少个数字位置是不正确的(被称为Cows),你的朋友需要根据这些线索最终猜出正确的数字。

例如,给出的数字是1807,你的朋友猜的是7810,这里用A代表Bulls,B代表Cows,则给出的线索是1A3B。

题目中给出的secret(被猜测数字)和guess(猜测的数字)长度一定是一样的。

public:
    string getHint(string secret, string guess) {
        
        vector<int> sec(10);
        vector<int> gue(10);
        int A = 0;      // bull
        for (int i = 0; i < secret.length(); ++i) {
            sec[secret[i] - '0']++;
            gue[guess[i] - '0']++;
            if (guess[i] == secret[i]) {
                ++A;
            }
        }
        int summation = 0;
        for (int i = 0; i < 10; ++i) {
            summation += min(sec[i], gue[i]);
        }
        return to_string(A) + "A" + to_string(summation - A) + "B";
    }
};

你可能感兴趣的:(算法题)