299. 猜数字游戏
为保证权益,题目请参考 299. 猜数字游戏(From LeetCode).
解决方案1
Python
python
# 299. 猜数字游戏
# https://leetcode-cn.com/problems/bulls-and-cows/
################################################################################
from typing import Dict, Set
class Solution:
def getHint(self, secret: str, guess: str) -> str:
d: Dict[str, Set[int]] = {}
for i, s in enumerate(secret):
if s in d:
d[s].add(i)
else:
d[s] = set([i])
dNum: Dict[str, int] = {}
for k, v in d.items():
dNum[k] = len(v)
bullsNum = 0
for i, s in enumerate(guess):
if s in d and i in d[s]:
bullsNum += 1
dNum[s] -= 1
cowsNum = 0
for i, s in enumerate(guess):
if s in d and i not in d[s] and dNum[s] > 0:
dNum[s] -= 1
cowsNum += 1
return f"{str(bullsNum)}A{str(cowsNum)}B"
################################################################################
if __name__ == "__main__":
solution = Solution()
print(solution.getHint("1123", "0111"))
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41