LeetCode299. Bulls and Cows(思路及python解法)

173 篇文章 0 订阅

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.

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. 

Please note that both secret number and friend's guess may contain duplicate digits.

Example 1:

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

Output: "1A3B"

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

小时候经常玩的猜数字游戏。

先比对完全正确猜对的,也就是A。

然后利用两个字典,统计猜的各个数字个数以及正确的各个数字个数。

这样对于同一个数字,既存在于guess又存在于secret,出现次数最少的就是B。

class Solution:
    def getHint(self, secret: str, guess: str) -> str:
        s={}
        g={}
        a=b=0
        for i in range(len(secret)):
            if secret[i]==guess[i]:
                a+=1
            else:
                s[secret[i]]=s.get(secret[i], 0)+1
                g[guess[i]]=g.get(guess[i], 0)+1
        for i in g:
            if i in s:
                b+=min(g[i],s[i])
        
        return '{}A{}B'.format(a,b)

当然也看到了大神的三行代码。

    s, g = Counter(secret), Counter(guess)
    a = sum(i == j for i, j in zip(secret, guess))
    return '%sA%sB' % (a, sum((s & g).values()) - a)

 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值