Problem
You are playing the following Bulls and Cows game with your friend: You write down a number and ask your friend to guess what the number is. Each time your friend makes a guess, you provide a hint that indicates how many digits in said guess match your secret number exactly in both digit and position (called "bulls") and how many digits match the secret number but locate in the wrong position (called "cows"). Your friend will use successive guesses and hints to eventually derive the secret number.
Write a function to return a hint according to the secret number and friend"s guess, use A to indicate the bulls and B to indicate the cows.
Please note that both secret number and friend"s guess may contain duplicate digits.
Example 1:
Input: secret = "1807", guess = "7810"
Output: "1A3B"
Explanation: 1 bull and 3 cows. The bull is 8, the cows are 0, 1 and 7.
Example 2:
Input: secret = "1123", guess = "0111"
Output: "1A1B"
Explanation: The 1st 1 in friend"s guess is a bull, the 2nd or 3rd 1 is a cow.
Note: You may assume that the secret number and your friend"s guess only contain digits, and their lengths are always equal.
class Solution { public String getHint(String secret, String guess) { //pre-process: get bulls int bulls = 0, cows = 0, len = secret.length(); char[] s1 = secret.toCharArray(); char[] s2 = guess.toCharArray(); for (int i = 0; i < len; i++) { if (s1[i] == s2[i]) { bulls++; s1[i] = "#"; s2[i] = "#"; } } //get cows with a digit map int[] dict = new int[10]; for (int i = 0; i < len; i++) { if (s1[i] == "#") continue; else dict[s1[i]-"0"]++; } for (int i = 0; i < len; i++) { if (s2[i] == "#") continue; else { if (dict[s2[i]-"0"] > 0) { cows++; dict[s2[i]-"0"]--; } } } return bulls+"A"+cows+"B"; } }
文章版权归作者所有,未经允许请勿转载,若此文章存在违规行为,您可以联系管理员删除。
转载请注明本文地址:https://www.ucloud.cn/yun/72521.html
摘要:题目要求游戏简单来说就是你随手写下一个位数,并让你同学猜这个数字是什么。第二次再在此基础上计算重合的值和没有重合的值的个数。这样的话,如果下一次遇到重复但是位置不同的值,我们可以知道它是否已经在中或是中出现过。 题目要求 You are playing the following Bulls and Cows game with your friend: You write down ...
摘要:题目这里主要是想记录一下这个很聪明的解法我规规矩矩的解法 题目:You are playing the following Bulls and Cows game with your friend: You write down a number and ask your friend to guess what the number is. Each time your friend...
摘要:已获原作者授权原系列地址游戏本章我们演示一个进阶例子我们用编写了游戏这个游戏也被称作或者或者是一个古老的益智解谜游戏由两名玩家参与早在世纪人们就在用铅笔和纸来玩这个游戏了在年发明的游戏正是受到这个游戏的启发和在基本理念上是一样的但被盒装出售 已获原作者授权. 原系列地址: Python Tkinter Mastermind 游戏 本章我们演示一个进阶例子. 我们用 Tkinter 编...
摘要:使用这么久对于数组的相关方法一直都是拿来就用对于方法更是常用。不过对于多个数组合并的时候因为返回的是新数组,可以链式下去。 使用JS这么久, 对于JS数组的相关方法一直都是拿来就用,对于push方法更是常用。但是在一次用到contact方法的时候自问了一句: push和contact到底有哪些区别? 先看下MDN的定义: 【push】:adds one or more element...
阅读 1808·2021-11-25 09:43
阅读 1295·2021-11-22 15:08
阅读 3666·2021-11-22 09:34
阅读 3193·2021-09-04 16:40
阅读 2844·2021-09-04 16:40
阅读 514·2019-08-30 15:54
阅读 1314·2019-08-29 17:19
阅读 1707·2019-08-28 18:13