Ai
1 Star 2 Fork 5

LilithSangreal/LeetCode-Solutions

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
文件
克隆/下载
bulls-and-cows.py 1.15 KB
一键复制 编辑 原始数据 按行查看 历史
Allen Liu 提交于 2018-10-13 01:56 +08:00 . add complexity
# Time: O(n)
# Space: O(10) = O(1)
import operator
# One pass solution.
from collections import defaultdict, Counter
from itertools import izip, imap
class Solution(object):
def getHint(self, secret, guess):
"""
:type secret: str
:type guess: str
:rtype: str
"""
A, B = 0, 0
s_lookup, g_lookup = defaultdict(int), defaultdict(int)
for s, g in izip(secret, guess):
if s == g:
A += 1
else:
if s_lookup[g]:
s_lookup[g] -= 1
B += 1
else:
g_lookup[g] += 1
if g_lookup[s]:
g_lookup[s] -= 1
B += 1
else:
s_lookup[s] += 1
return "%dA%dB" % (A, B)
# Two pass solution.
class Solution2(object):
def getHint(self, secret, guess):
"""
:type secret: str
:type guess: str
:rtype: str
"""
A = sum(imap(operator.eq, secret, guess))
B = sum((Counter(secret) & Counter(guess)).values()) - A
return "%dA%dB" % (A, B)
Loading...
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化
1
https://gitee.com/LilithSangreal/LeetCode-Solutions.git
git@gitee.com:LilithSangreal/LeetCode-Solutions.git
LilithSangreal
LeetCode-Solutions
LeetCode-Solutions
master

搜索帮助