Python solution using a Counter

  • 4

    I think the most tricky part is just to understand what cows mean...

    class Solution(object):
    def getHint(self, secret, guess):
        :type secret: str
        :type guess: str
        :rtype: str
        from collections import Counter
        c = Counter(secret)
        bulls, cows = 0,0
        for i in xrange(len(secret)):
            if secret[i]==guess[i]:
                bulls += 1
                c[secret[i]] -= 1
        for i in xrange(len(secret)):
            if secret[i]!=guess[i]:
                if guess[i] in c and c[guess[i]]>0:
                    c[guess[i]] -= 1
                    cows += 1 
        return str(bulls)+'A'+str(cows)+'B'

Log in to reply

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