A simple python solution


  • 1
    H

    I share a solution using dict

    def getHint(self, secret, guess):
        sDic = {'0':0,'1':0,'2':0,'3':0,'4':0,'5':0,'6':0,'7':0,'8':0,'9':0}
        gDic = {'0':0,'1':0,'2':0,'3':0,'4':0,'5':0,'6':0,'7':0,'8':0,'9':0}
        length = len(secret)
        bulls, cows = 0, 0
        # count the number of 0-9 in secret and guess, and calculate bulls
        for i in range(length):
            s, g = secret[i], guess[i]
            sDic[s] += 1
            gDic[g] += 1
            if s == g:
                bulls += 1
        # calculate cows, add up the min of sDic and gDic, then minus bulls
        for k in sDic.keys():
            cows += min(sDic[k], gDic[k])
        cows -= bulls
        # return result
        return "%dA%dB" % (bulls,cows)

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.