lc299. Bulls and Cows

  1. Bulls and Cows Easy

402python

430git

Favoritebash

Share 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.ide

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.ui

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

Example 1:code

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

Output: "1A3B"string

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

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: You may assume that the secret number and your friend's guess only contain digits, and their lengths are always equal.

思路:遍历一遍,寻找下标和值都相等的,记录为A,顺便把s和g记录到对应的字典dicA,dicB, 遍历dicA,查找健相同的值,sub(min(a,b)...)即为B的值

代码:python3

class Solution:
    def getHint(self, secret: str, guess: str) -> str:
        a=0
        b=0
        dicA={}
        dicB={}
        for (index,value) in enumerate(secret):
            if secret[index]==guess[index]:
                a=a+1
            else:
                if value in dicA:
                    dicA[value] = dicA[value]+1
                else:
                    dicA[value] = 1
                if guess[index] in dicB:
                    dicB[guess[index]] = dicB[guess[index]]+1
                else:
                    dicB[guess[index]] = 1
        for key in dicA:
            if key in dicB:
                b = b + min(dicA[key],dicB[key])
            else:
                pass
        return str(a)+"A"+str(b)+"B"
复制代码
相关文章
相关标签/搜索