Bulls and Cows
注意A了的就不能再放进B里面了
class Solution(object):
def getHint(self, secret, guess):
"""
:type secret: str
:type guess: str
:rtype: str
"""
secretDict, guessDict = collections.Counter(), collections.Counter()
countA, countB = 0, 0
for index, char in enumerate(secret):
if char == guess[index]:
countA += 1
else:
secretDict[char] += 1
guessDict[guess[index]] += 1
for char in secretDict:
if char in guessDict:
countB += min(guessDict[char], secretDict[char])
return '{}A{}B'.format(countA, countB)
还有一个discussion里的神版本... 主要的是Python里面哈希表还可以用&符号直接实现交集运算......
class Solution(object):
def getHint(self, secret, guess):
"""
:type secret: str
:type guess: str
:rtype: str
"""
s, g = collections.Counter(secret), collections.Counter(guess)
A = sum((1 for i, j in zip(secret, guess) if i == j))
return '{}A{}B'.format(A, sum((s & g).values()) - A)