天天看點

[LeetCode] 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.

For example:

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

Write a function to return a hint according to the secret number and friend's guess, use <code>A</code> to indicate the bulls and <code>B</code> to indicate the cows, in the above example, your function should return <code>1A3B</code>.

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

Credits:

這道題提出了一個叫公牛母牛的遊戲,其實就是之前文曲星上有的猜數字的遊戲,有一個四位數字,你猜一個結果,然後根據你猜的結果和真實結果做對比,提示有多少個數字和位置都正确的叫做bulls,還提示有多少數字正确但位置不對的叫做cows,根據這些資訊來引導我們繼續猜測正确的數字。這道題并沒有讓我們實作整個遊戲,而隻用實作一次比較即可。給出兩個字元串,讓我們找出分别幾個bulls和cows。這題需要用哈希表,來建立數字和其出現次數的映射。我最開始想的方法是用兩次周遊,第一次周遊找出所有位置相同且值相同的數字,即bulls,并且記錄secret中不是bulls的數字出現的次數。然後第二次周遊我們針對guess中不是bulls的位置,如果在哈希表中存在,cows自增1,然後映射值減1,參見如下代碼:

解法一:

我們其實可以用一次循環就搞定的,在處理不是bulls的位置時,我們看如果secret目前位置數字的映射值小于0,則表示其在guess中出現過,cows自增1,然後映射值加1,如果guess目前位置的數字的映射值大于0,則表示其在secret中出現過,cows自增1,然後映射值減1,參見代碼如下:

解法二:

最後我們還可以稍作修改寫的更簡潔一些,a是bulls的值,b是bulls和cows之和,參見代碼如下:

解法三:

繼續閱讀