Python Solution in One Pass


  • 0
    M
    class Solution(object):
        def getHint(self, secret, guess):
            """
            :type secret: str
            :type guess: str
            :rtype: str
            """
            bulls, cows = 0,0
            d1,d2 = dict(),dict()
            for i in xrange(len(secret)):
                if secret[i] == guess[i]:
                    bulls += 1
                    continue
                else:
                    d1[secret[i]] = d1.get(secret[i], 0) + 1
                    d2[guess[i]] = d2.get(guess[i], 0) + 1
                
                if secret[i] in d2 and d2[secret[i]]:
                    cows += 1
                    d1[secret[i]] -= 1
                    d2[secret[i]] -= 1
                
                if guess[i] in d1 and d1[guess[i]]:
                    cows += 1
                    d1[guess[i]] -= 1
                    d2[guess[i]] -= 1
                    
                    
            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.