Skip to content

299 bulls and cows

299. Bulls and Cows

题目:

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

难度:

Easy

我花了很久时间来AC,因为想了边界条件

class Solution(object):
    def getHint(self, secret, guess):
        """
        :type secret: str
        :type guess: str
        :rtype: str
        """
        maps = {}
        for i in range(len(secret)):
            if secret[i] not in maps:
                maps[secret[i]] = [i]
            else:
                maps[secret[i]].append(i)
        mapg = {}
        for i in range(len(guess)):
            if guess[i] not in mapg:
                mapg[guess[i]] = [i]
            else:
                mapg[guess[i]].append(i)

        print maps, mapg

        a,b = 0,0
        for key in maps.keys():
            if key in mapg.keys():
                common = list(set(mapg[key]) & set(maps[key]))
                #check for bull
                a += len(common)
                mapg[key] = [item for item in mapg[key] if item not in common]
                maps[key] = [item for item in maps[key] if item not in common]
                b += min(len(maps[key]), len(mapg[key]))
        return str(a) + 'A' + str(b) + 'B'        

两种解法都.......

都这么短。。。。。 我Python还是用的不行啊

class Solution(object):
    def getHint(self, secret, guess):
        """
        :type secret: str
        :type guess: str
        :rtype: str
        """
        bull = sum(map(operator.eq, secret, guess))
        sa = collections.Counter(secret)
        sb = collections.Counter(guess)
        cow = sum((sa & sb).values()) - bull
        return str(bull) + 'A' + str(cow) + 'B'

bull = secret与guess下标与数值均相同的数字个数

cow = secret与guess中出现数字的公共部分 - bull

来分析一下这个解法

def getHint(self, secret, guess):
    bulls = sum(map(operator.eq, secret, guess))
    both = sum(min(secret.count(x), guess.count(x)) for x in '0123456789')
    return '%dA%dB' % (bulls, both - bulls)

首先map的用法是,对于iterable中的每个元素应用function方法,将结果作为list返回

>>> def add100(x):
...     return x+100
... 
>>> hh = [11,22,33]
>>> map(add100,hh)
[111, 122, 133]

用'1123','0111' 来测试:

map(operator.eq, secret, guess)
[False, True, False, False]

就是将equal函数并行应用在两个string上,然后后面的解法也是粗暴简约和厉害

参考http://my.oschina.net/zyzzy/blog/115096



回到顶部