LeetCode 第299题 Bulls and Cows
source link: https://codechina.org/2019/08/leetcode-299-bulls-and-cows/
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
来源:https://leetcode.com/problems/bulls-and-cows/
题目:猜数字
你和朋友在玩猜数字游戏:你写下一个数字,让你的朋友猜数字是多少。每次你朋友猜一个数字,你要告诉他一个提示,说明有多少个数字对了。如果你朋友猜的一位数字,数字也对,位置也对,那么就叫做bull,如果数字是对的,但是位置错了就叫cow。你的朋友需要根据这些提示来最终找到正确答案。
写一个函数来生成提示,用A代表bull,用B代表cow。
注意,可以出现重复的数字。
Example 1:
Input: secret = "1807", guess = "7810" Output: "1A3B" Explanation:1
bull and3
cows. The bull is8
, the cows are0
,1
and7.
Example 2:
Input: secret = "1123", guess = "0111" Output: "1A1B" Explanation: The 1st1
in friend's guess is a bull, the 2nd or 3rd1
is a cow.
我们分别看bull和cow的规则,所以我们其实是要对比两个字符串secret和guess里面的数字。首先我们看怎么计算bull。思路不复杂,就是两个字符串先转化为字符数组。然后逐个比对是否相同,相同则bull+1。但是注意,我们还把匹配相同的数字用字符 ‘.’ 来代替,这样就不会在计算cow的时候重复计算了。
然后我们看怎么计算cow,首先我们把secret的剩下的数字扔到一个hashset里。然后用guess剩余的数字去比对,比对成功一个,就cow+1。计算cow的代码:
比对函数:
计算出bull和cow以后,输出就很简单了:
Github:https://github.com/tinyfool/leetcode/tree/master/src/p0299
本题属于哈希表类题目,想了解更多关于哈希表的题目,可以参看哈希表专题。
Recommend
About Joyk
Aggregate valuable and interesting links.
Joyk means Joy of geeK