day19笔记
1.题目描述
2.代码构思(debug)
根据题意,对于公牛,需要满足数字和确切位置都猜对。我们可以遍历 secret 和guess,统计满足secret[i]=guess[i] 的下标个数,即为公牛的个数。
对于奶牛,需要满足数字猜对但是位置不对。我们可以在secret[i]
=guess[i] 时,分别统计secret 和 guess 的各个字符的出现次数,记在两个长度为 10的数组中。根据题目所述的「这次猜测中有多少位非公牛数字可以通过重新排列转换成公牛数字」,由于多余的数字无法匹配,对于 0 到9 的每位数字,应取其在 secret 和 guess 中的出现次数的最小值。将每位数字出现次数的最小值累加,即为奶牛的个数。
class Solution:
def getHint(self, secret: str, guess: str) -> str:
if not secret or not guess:
return
CountA = 0
CountB = 0
counts = [0]*10
countg = [0]*10
for s,g in zip(secret,guess):
if s == g:
CountA += 1
else:
counts[int(s)] += 1
countg[int(g)] += 1
CountB = sum(min(s,g) for s,g in zip(counts,countg))
return str(CountA) + "A" + str(CountB) + "B"