[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:

Secret number:  1807
Friend's guess: 7810

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

According to Wikipedia: "Bulls and Cows (also known as Cows and Bulls or Pigs and Bulls or Bulls and Cleots) is an old code-breaking mind or paper and pencil game for two or more players, predating the similar commercially marketed board game Mastermind. The numerical version of the game is usually played with 4 digits, but can also be played with 3 or any other number of digits."

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.

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

题目大意:

你和朋友在玩下面的猜数字游戏(Bulls and Cows):你写下一个4位数的神秘数字然后让朋友来猜,你的朋友每次猜一个数字,你给一个提示,告诉他有多少个数字处在正确的位置上(称为"bulls" 公牛),以及有多少个数字处在错误的位置上(称为"cows" 奶牛),你的朋友使用这些提示找出那个神秘数字。

例如:

神秘数字:  1807
朋友猜测:  7810

提示信息:  1公牛 3奶牛。(公牛是8, 奶牛是0, 1和7)

根据维基百科:“公牛和奶牛(也称为奶牛和公牛,或者猪和公牛, 或者公牛和Cleots)” 是一歀古老的两人或多人参与的密码破解智力游戏或纸笔游戏,早于与之类似的市售棋牌游戏Mastermind。这款游戏的数字版本通常包含4位数,但也可以是3位或者其他任何位数。”

编写函数,根据神秘数字与朋友的猜测,返回一个提示信息,使用A表示公牛,B表示母牛,在上例中,你的函数应当返回1A3B。

你可以假设神秘数字和你朋友的猜测只包含数字,并且长度一定相等。

解题思路:

bull = secret与guess下标与数值均相同的数字个数

cow = secret与guess中出现数字的公共部分 - bull

Python代码(使用Counter):

class Solution(object):
    def getHint(self, secret, guess):
        """
        :type secret: str
        :type guess: str
        :rtype: str
        """
        bull = sum(map(operator.eq, secret, guess))
        sa = collections.Counter(secret)
        sb = collections.Counter(guess)
        cow = sum((sa & sb).values()) - bull
        return str(bull) + 'A' + str(cow) + 'B'

下面的思路是按照0-9分别统计,参考:https://leetcode.com/discuss/67016/3-lines-in-python

Python代码:

def getHint(self, secret, guess):
    bulls = sum(map(operator.eq, secret, guess))
    both = sum(min(secret.count(x), guess.count(x)) for x in '0123456789')
    return '%dA%dB' % (bulls, both - bulls)

 

本文链接:http://bookshadow.com/weblog/2015/10/31/leetcode-bulls-and-cows/
请尊重作者的劳动成果,转载请注明出处!书影博客保留对文章的所有权利。

如果您喜欢这篇博文,欢迎您捐赠书影博客: ,查看支付宝二维码

Pingbacks已关闭。

暂无评论

张贴您的评论