299. Bulls and Cows
Input: secret = "1807", guess = "7810"
Output: "1A3B"
Explanation: 1 bull and 3 cows. The bull is 8, the cows are 0, 1 and 7.Input: secret = "1123", guess = "0111"
Output: "1A1B"
Explanation: The 1st 1 in friend's guess is a bull, the 2nd or 3rd 1 is a cow.解题要点:
class Solution(object):
def getHint(self, secret, guess):
"""
:type secret: str
:type guess: str
:rtype: str
"""
bulls = cows = 0
num = [0 for i in range(10)]
for i in range(len(guess)):
if secret[i] == guess[i]:
bulls += 1
else:
if num[int(secret[i])] < 0: cows += 1
if num[int(guess[i])] > 0: cows += 1
num[int(secret[i])] += 1
num[int(guess[i])] -= 1
return str(bulls) + "A" + str(cows) + "B"Last updated