Python: one pass


  • 0
    N

    using an array "map" to track cows which can appear in these two possible scenarios:

    1. number already seen in guess and now it's observed in secret
    2. number already seen in secret and now it's observed in guess
    class Solution(object):
        def getHint(self, secret, guess):
            """
            :type secret: str
            :type guess: str
            :rtype: str
            """
            bull = 0
            cow = 0
            L = len(secret)
            map = [0] * 10
            for i in xrange(L):
                if secret[i] == guess[i]:
                    bull += 1
                else:
                    # scenario 1
                    if map[int(secret[i])] < 0:
                        cow += 1
                    map[int(secret[i])] += 1
                    # scenario 2
                    if map[int(guess[i])] > 0:
                        cow += 1
                    map[int(guess[i])] -= 1
            return str(bull)+'A'+str(cow)+'B'
    

Log in to reply
 

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