博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
[LeetCode] Bulls and Cows
阅读量:6647 次
发布时间:2019-06-25

本文共 2118 字,大约阅读时间需要 7 分钟。

You are playing the following Bulls and Cows game with your friend: You write a 4-digit secret number and ask your friend to guess it, each time your friend guesses a number, you give a hint, the hint tells your friend how many digits are in the correct positions (called "bulls") and how many digits are in the wrong positions (called "cows"), your friend will use those hints to find out the secret number.

For example:

Secret number:  1807Friend's guess: 7810

Hint: 1 bull and 3 cows. (The bull is 8, the cows are 01 and 7.)

 

According to : "Bulls and Cows (also known as Cows and Bulls or Pigs and Bulls or Bulls and Cleots) is an old code-breaking mind or paper and pencil game for two or more players, predating the similar commercially marketed board game Mastermind. The numerical version of the game is usually played with 4 digits, but can also be played with 3 or any other number of digits."

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, in the above example, your function should return 1A3B.

You may assume that the secret number and your friend's guess only contain digits, and their lengths are always equal.

Credits:

Special thanks to  for adding this problem and creating all test cases.

 

 to see which companies asked this question

1 class Solution { 2 public: 3     string getHint(string secret, string guess) { 4         int cntA = 0, cntB = 0; 5         unordered_map
hash; 6 vector
tag(secret.size(), false); 7 for (auto a : secret) { 8 ++hash[a]; 9 };10 for (int i = 0; i < secret.size(); ++i) {11 if (secret[i] == guess[i]) {12 ++cntA;13 --hash[secret[i]];14 tag[i] = true;15 }16 }17 for (int i = 0; i < guess.size(); ++i) {18 if (!tag[i] && hash[guess[i]] > 0) {19 ++cntB;20 --hash[guess[i]];21 }22 }23 return to_string(cntA) + "A" + to_string(cntB) + "B";24 }25 };

 

转载地址:http://ceuto.baihongyu.com/

你可能感兴趣的文章
java 多线程 Synchronized方法和方法块 synchronized(this)和synchronized(object)的理解
查看>>
ASP.NET MVC5+EF6+EasyUI 后台管理系统(18)-权限管理系统-表数据
查看>>
Windows Phone 8初学者开发—第12部分:改进视图模型和示例数据
查看>>
Redis: under the hood---转载
查看>>
C#笔试题面试题锦集(全)总20篇
查看>>
windows下体验Redis
查看>>
在Phonegap下实现oAuth认证
查看>>
Flash播放mp4的两个问题:编码问题和需要下载完后才能播放的问题
查看>>
ios 去掉UITableView Group形式下面的白色阴影
查看>>
Pascal可视化编程 CodeTyphon 、Lazarus
查看>>
LD_PRELOAD & LD_LIBRARY_PATH 动态库路径
查看>>
linux 下 java 链接oracle数据库
查看>>
网站标签命名规范【转载】
查看>>
android手机内的通讯录数据库
查看>>
与众不同 windows phone (1) - Hello Windows Phone
查看>>
linux 用户管理
查看>>
我是该学JAVA呢,还是学IOS开发呢?
查看>>
HDU 1058 Humble Number
查看>>
活用UML-软件设计高手(深圳 2014年4月26-27日)
查看>>
MySQL之权限管理
查看>>