forked from shuboc/LeetCode-2
-
Notifications
You must be signed in to change notification settings - Fork 1
/
bulls-and-cows.py
50 lines (41 loc) · 1.15 KB
/
bulls-and-cows.py
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
42
43
44
45
46
47
48
49
# 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)