Tcdian / keep

今天不想做,所以才去做。
MIT License
5 stars 1 forks source link

299. Bulls and Cows #324

Open Tcdian opened 3 years ago

Tcdian commented 3 years ago

299. Bulls and Cows

你在和朋友一起玩 猜数字(Bulls and Cows)游戏,该游戏规则如下:

  1. 你写出一个秘密数字,并请朋友猜这个数字是多少。

  2. 朋友每猜测一次,你就会给他一个提示,告诉他的猜测数字中有多少位属于数字和确切位置都猜对了(称为“Bulls”, 公牛),有多少位属于数字猜对了但是位置不对(称为“Cows”, 奶牛)。

  3. 朋友根据提示继续猜,直到猜出秘密数字。 请写出一个根据秘密数字和朋友的猜测数返回提示的函数,返回字符串的格式为 xAyBxy 都是数字,A 表示公牛,用 B 表示奶牛。

  4. xA 表示有 x 位数字出现在秘密数字中,且位置都与秘密数字一致。

  5. yB 表示有 y 位数字出现在秘密数字中,但位置与秘密数字不一致。 请注意秘密数字和朋友的猜测数都可能含有重复数字,每位数字只能统计一次。

Example 1

Input: secret = "1807", guess = "7810"

Output: "1A3B"

Explanation: 1 bull and 3 cows. The bull is 8, the cows are 0, 1 and 7.

Example 2

Input: secret = "1123", guess = "0111"

Output: "1A1B"

Explanation: The 1st 1 in friend's guess is a bull, the 2nd or 3rd 1 is a cow.

Note

Tcdian commented 3 years ago

Solution

/**
 * @param {string} secret
 * @param {string} guess
 * @return {string}
 */
var getHint = function(secret, guess) {
    let bulls = 0;
    let cows = 0;
    let cache = new Map();
    for (let i = 0; i < secret.length; i++) {
        if (secret[i] === guess[i]) {
            bulls += 1;
        } else {
            cache.set(secret[i], (cache.get(secret[i]) || 0) + 1);
        }
    }
    for (let i = 0; i < guess.length; i++) {
        if (secret[i] === guess[i]) {
            continue;
        }
        if (cache.has(guess[i]) && cache.get(guess[i]) > 0) {
            cows += 1;
            cache.set(guess[i], cache.get(guess[i]) - 1);
        }
    }
    return `${bulls}A${cows}B`;
};
function getHint(secret: string, guess: string): string {
    let bulls = 0;
    let cows = 0;
    let cache: Map<string, number> = new Map();
    for (let i = 0; i < secret.length; i++) {
        if (secret[i] === guess[i]) {
            bulls += 1;
        } else {
            cache.set(secret[i], (cache.get(secret[i]) || 0) + 1);
        }
    }
    for (let i = 0; i < guess.length; i++) {
        if (secret[i] === guess[i]) {
            continue;
        }
        if (cache.has(guess[i]) && cache.get(guess[i])! > 0) {
            cows += 1;
            cache.set(guess[i], cache.get(guess[i])! - 1);
        }
    }
    return `${bulls}A${cows}B`;
};