Python, only 1-loop or 1-pass of the pattern/secret string


  • 0
    A
    class Solution(object):
        def getHint(self, secret, guess):
            """
            :type secret: str
            :type guess: str
            :rtype: str
            """
            map_s = {}
            map_g = {}
            cows = 0
            bulls = 0
            for i in xrange(len(guess)):
                if guess[i] == secret[i]:
                    bulls += 1
                else:
                    if map_s.has_key(guess[i]) and map_s[guess[i]]>0:
                        cows += 1
                        map_s[guess[i]] -= 1
                    else:
                        map_g[guess[i]] = map_g.get(guess[i],0)+1
                        
                    if map_g.has_key(secret[i]) and map_g[secret[i]]>0:
                        cows += 1
                        map_g[secret[i]] -= 1
                    else:
                        map_s[secret[i]] = map_s.get(secret[i],0)+1
                
            return "%iA%iB" % ( bulls,cows )

Log in to reply
 

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