leetcode -- Bulls and Cows -- 难理解题意,要看

https://leetcode.com/problems/bulls-and-cows/

这里要注意重复的问题。要首先计算bull,然后再计算cow,被match过得secret digit不能再被用来计算cow。这一点要注意

最后一种方法最好理解

my code效率很低

class Solution(object):
    def getHint(self, secret, guess):
        """ :type secret: str :type guess: str :rtype: str """

        mydict1, mydict2 = {},{}

        for i in xrange(len(secret)):
            if secret[i] in mydict1:
                mydict1[secret[i]].append(i)
                mydict2[secret[i]] += 1
            else:
                mydict1[secret[i]] = [i]
                mydict2[secret[i]] = 1


        bull,cow = 0,0
        # calculate the bull first and then calculate the cow
        for i in xrange(len(guess)):
            if guess[i] in mydict1:
                if i in mydict1[guess[i]]:
                    bull += 1
                    mydict2[guess[i]] -= 1

        for i in xrange(len(guess)):
            if guess[i] in mydict1:
                if mydict2[guess[i]] > 0 and i not in mydict1[guess[i]]:
                    cow += 1
                    mydict2[guess[i]] -= 1

        return str(bull) + 'A' + str(cow) + 'B'

更简单的办法是http://bookshadow.com/weblog/2015/10/31/leetcode-bulls-and-cows/

bulls = sum(map(operator.eq, secret, guess))#来计算bull最有效

这个办法也不错
http://www.hrwhisper.me/leetcode-bulls-and-cows/

这里先把bull算出来,并用digit作为hash map counter来计算在secret中除了已经被bull match的secret[i]以外,有哪些数字,其对应的occurence的次数是多少。然后再scan guess 排除掉被bull match的guess[i]然后再看digit里面对应的guess[i]是不是大于0,如果是就算一次cow

class Solution(object):
    def getHint(self, secret, guess):
        """ :type secret: str :type guess: str :rtype: str """
        if not secret or not guess: return '0A0B'
        bulls, cows, digits = 0, 0, [0 ] * 10
        for i in xrange(len(secret)):
            if secret[i] == guess[i]:
                bulls += 1
            else:
                digits[int(secret[i])] += 1

        for i in xrange(len(secret)):
            if secret[i] != guess[i] and digits[int(guess[i])] != 0:#注意这里是求guess[i]的value
                cows += 1
                digits[int(guess[i])] -= 1
        return str(bulls) + 'A' + str(cows) + 'B'

自己重写code

class Solution(object):
    def getHint(self, secret, guess):
        """ :type secret: str :type guess: str :rtype: str """
        digit = {}
        bull = 0
        for i in xrange(len(secret)):
            if guess[i] == secret[i]:
                bull += 1
            else:
                if guess[i] not in digit:
                    digit[guess[i]] = 1
                else:
                    digit[guess[i]] += 1
        cow = 0
        for i in xrange(len(secret)):
            if guess[i] != secret[i] and secret[i] in digit and digit[secret[i]]>0:
               digit[secret[i]] -= 1
               cow += 1
        return str(bull) + 'A' + str(cow) + 'B'

你可能感兴趣的:(LeetCode)