Bulls and Cows
要点:类似于Word Pattern,guess和secret要存成两个counts<int, int>,因为guess中了的可能在secret之前出现,vice versa。另一种方法是可以多遍统计:先过一遍secret,然后过一遍guess统计cows,最后统计bulls调整cows
class Solution(object):
def getHint(self, secret, guess):
"""
:type secret: str
:type guess: str
:rtype: str
"""
from collections import defaultdict
bulls,cows = 0,0
cowskey = defaultdict(int)
cowsval = defaultdict(int)
for i in xrange(len(secret)):
if secret[i]==guess[i]:
bulls+=1
continue
if guess[i] in cowskey and cowskey[guess[i]]>0:
cows+=1
cowskey[guess[i]]-=1
else:
cowsval[guess[i]]+=1
if secret[i] in cowsval and cowsval[secret[i]]>0:
cows+=1
cowsval[secret[i]]-=1
else:
cowskey[secret[i]]+=1
return str(bulls)+'A'+str(cows)+'B'