Last active
November 23, 2015 13:18
-
-
Save lyleaf/a7d988be233ef0f77f12 to your computer and use it in GitHub Desktop.
299 Bulls and Cows
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Comment | |
https://leetcode.com/problems/bulls-and-cows/ | |
First my solution is to loop it for once to get the dict of the secret. Then loop it for a second time. | |
Then I see that it can be done in one loop. |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class Solution(object): | |
def getHint(self, secret, guess): | |
""" | |
:type secret: str | |
:type guess: str | |
:rtype: str | |
""" | |
d = {} | |
bull, cow = 0,0 | |
for index,s in enumerate(secret): | |
if guess[index] == s: | |
bull += 1 | |
else: | |
d[s] = d.get(s,0) + 1 | |
for index,s in enumerate(secret): | |
if (guess[index] != s) & (d.get(guess[index],0) != 0): | |
cow += 1 | |
d[guess[index]] -= 1 | |
return str(bull) + "A" + str(cow) + "B" |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class Solution(object): | |
def getHint(self, secret, guess): | |
""" | |
:type secret: str | |
:type guess: str | |
:rtype: str | |
""" | |
ds = {} | |
dg = {} | |
bull, cow = 0,0 | |
for index,s in enumerate(secret): | |
if guess[index] == s: | |
bull += 1 | |
else: | |
if ds.get(guess[index],0) == 0: | |
dg[guess[index]] = dg.get(guess[index],0) + 1 | |
if dg.get(s,0) == 0: | |
ds[s] = ds.get(s,0) + 1 | |
if ds.get(guess[index],0) != 0: | |
ds[guess[index]] = ds.get(guess[index],0) - 1 | |
cow += 1 | |
if dg.get(s,0) != 0: | |
cow += 1 | |
dg[s] = dg.get(s,0) - 1 | |
return str(bull) + "A" + str(cow) + "B" |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment