Bulls and Cows

Problem: Bulls and Cows

To solve the problem, we need to record each bulls first. Then we can inspect non-bull numbers. If there are 2 non-bull "1"s in secret and 1 "1"s in guess, there is absolutely one cow for this, which means cows are decided by smaller of these 2 numbers. Thus, we can record the numbers of all non-bull elements in two dictionary separately for secret and guess and count cows for each of the elements.

Code in Python:

from collections import defaultdict

class Solution(object):
    def getHint(self, secret, guess):
        """
        :type secret: str
        :type guess: str
        :rtype: str
        """
        s_dict, g_dict = {}, {}
        for x in xrange(10):
            s_dict[str(x)], g_dict[str(x)] = 0, 0
        a, b = 0, 0
        for i in xrange(len(secret)):
            if secret[i] == guess[i]:
                a += 1
            else:
                s_dict[secret[i]] += 1
                g_dict[guess[i]] += 1
        for x in xrange(10):
            b += min(s_dict[str(x)], g_dict[str(x)])
        return "%dA%dB" % (a, b)

results matching ""

    No results matching ""