Python solution in O(n) with dictionary


  • 0
    A
    def getHint(self, secret, guess):
        dic = {}
        for c in secret:
            if c not in dic:
                dic[c] = 0
            dic[c] += 1
            
        A = 0
        B = 0
        for i in xrange(len(secret)):
            if secret[i] == guess[i]:
                A += 1
                dic[secret[i]] -= 1
        
        for i in xrange(len(secret)):
            if secret[i] != guess[i] and guess[i] in dic and dic[guess[i]]>0:
                dic[guess[i]] -= 1
                B += 1
                
        return str(A)+'A'+str(B)+'B'

Log in to reply
 

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