题目传送门:
https://leetcode-cn.com/problems/bulls-and-cows/description/
思路:
1)bulls可以在同时循环secret和guess时直接做出。
2)crows需要历遍secret和guess后,记录下各个数字的出现频数,将各个数字的频数相减以后可以出。
class Solution:
def getHint(self, secret, guess):
"""
:type secret: str
:type guess: str
:rtype: str
"""
bull = 0
secret_list = {}
guess_list = {}
to_del = []
for i in range(len(secret)):
if secret[i] == guess[i]:
to_del.append(i)
bull += 1
else:
if secret[i] in secret_list:
secret_list[secret[i]] += 1
else:
secret_list[secret[i]] = 1
if guess[i] in guess_list:
guess_list[guess[i]] += 1
else:
guess_list[guess[i]] = 1
cows = 0
for i in guess_list.keys():
if i in secret_list.keys():
cows += min(guess_list[i],secret_list[i])
return '{}A{}B'.format(bull,cows)
可优化点:
1)使用numpy的array代替字典(pandas的Series这里不给用),使用字典的目的是为了利用字典的索引,实现count功能,由于本题的密码只有10个数字,因此可以使用array的位置来直接实现索引,这样在做减法时,速度更快。