天天看點

LeetCode 299 Bulls and Cows(公牛和母牛)(HashMap)

版權聲明:轉載請聯系本人,感謝配合!本站位址:http://blog.csdn.net/nomasp https://blog.csdn.net/NoMasp/article/details/52560310

翻譯

你在和朋友們玩一個叫做“公牛和母牛”的遊戲:你寫下一組數字,然後讓你的朋友來猜它。每次你朋友做一個猜測,你根據他的猜測給一個提示:他在數字在值和位置上都猜對的數字,就叫做bulls(公牛),猜對了值但位置不對的數字叫做cows(母牛)。你的朋友将使用各種猜測和提示最終猜出來正确的數字。

例如:

你給的秘密數字是:“1807”

朋友的猜測是:“7810”

提示:1個公牛和3個母牛。(公牛是8,母牛是0、1、7。)

寫一個函數用于根據你給的秘密數字和朋友的猜測做一個提示,使用A來表示公牛,使用B來表示母牛。在上面的例子中,你應該傳回但是“1A3B”。

請注意,你給的秘密數字和朋友猜測的數字都可能包含重複的數字,例如:

你給的秘密數字是:“1123”

朋友的猜測是:“0111”

在這個情況下,朋友猜測的第一個1是公牛,第二個和第三個1是母牛,那麼你的函數應該傳回“1A1B”。

你可以假設秘密數字和猜測數字都隻包含數字,并且它們的長度是相等的。

原文

You are playing the following Bulls and Cows game with your friend: You write down a number and ask your friend to guess what the number is. Each time your friend makes a guess, you provide a hint that indicates how many digits in said guess match your secret number exactly in both digit and position (called “bulls”) and how many digits match the secret number but locate in the wrong position (called “cows”). Your friend will use successive guesses and hints to eventually derive the secret number.

For example:

Secret number: “1807”

Friend’s guess: “7810”

Hint: 1 bull and 3 cows. (The bull is 8, the cows are 0, 1 and 7.)

Write a function to return a hint according to the secret number and friend’s guess, use A to indicate the bulls and B to indicate the cows. In the above example, your function should return “1A3B”.

Please note that both secret number and friend’s guess may contain duplicate digits, for example:

Secret number: “1123”

Friend’s guess: “0111”

In this case, the 1st 1 in friend’s guess is a bull, the 2nd or 3rd 1 is a cow, and your function should return “1A1B”.

You may assume that the secret number and your friend’s guess only contain digits, and their lengths are always equal.

分析

需要注意的是上面的第二個例子,秘密數字是1123,猜測數字是0111,結果是1A1B,而不是1A2B,也就是說後面兩個猜錯位置但值正确的也隻能算一個母牛。

也就是說,如果秘密數字是3456,猜測數字是2333,結果也應該是0A1B,而不是0A3B。

知道規則其實就很容易了,直接看代碼吧,當然也可以先看看這些類似的問題~

LeetCode 205 Isomorphic Strings(同構的字元串)(string、vector、map)(*) LeetCode 290 Word Pattern(單詞模式)(istringstream、vector、map)(*)
public String getHint(String secret, String guess) {
        int bulls = 0, cows = 0;
        int[] s = new int[10], g = new int[10];

        for (int i = 0; i < secret.length(); i++) {
            char c1 = secret.charAt(i), c2 = guess.charAt(i);
            if (c1 == c2) {
                bulls++;
            } else {
                s[c1 - '0']++;
                g[c2 - '0']++;
            }
        }
        for (int i = 0; i < s.length; i++) {
            cows += Math.min(s[i], g[i]);
        }
        return bulls + "A" + cows + "B";
    }