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";
    }
};

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值