LeetCode OJ:Bulls and Cows (公牛与母牛)
2015-11-24 21:57
309 查看
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.
For example:
Hint:
Write a function to return a hint according to the secret number and friend's guess, use
Please note that both secret number and friend's guess may contain duplicate digits, for example:
In this case, the 1st
经典的小游戏,hashtable解决之,代码如下:
For example:
Secret number: "1807" Friend's guess: "7810"
Hint:
1bull and
3cows. (The bull is
8, the cows are
0,
1and
7.)
Write a function to return a hint according to the secret number and friend's guess, use
Ato indicate the bulls and
Bto indicate the cows. In the above example, your function should return
"1A3B".
Please note that both secret number and friend's guess may contain duplicate digits, for example:
Secret number: "1123" Friend's guess: "0111"
In this case, the 1st
1in friend's guess is a bull, the 2nd or 3rd
1is a cow, and your function should return
"1A1B".
经典的小游戏,hashtable解决之,代码如下:
class Solution { public: string getHint(string secret, string guess) { unordered_map<char, int> hash; int countA, countB; countA = countB = 0; vector<bool> solved(secret.size(), false); for(int i = 0; i < secret.size(); ++i){ ++hash[secret[i]]; } for(int i = 0; i < secret.size(); ++i){ if(secret[i] == guess[i]){ countA++; solved[i] = true; --hash[secret[i]]; } } for(int i = 0; i < guess.size(); ++i){ if(!solved[i] && hash[guess[i]] > 0){ countB++; --hash[guess[i]]; } } return toString(countA) + "A" + toString(countB) + "B"; } string toString(int i) { stringstream ss; ss << i; string tmp; ss >> tmp; return tmp; } };
相关文章推荐
- CentOS Linux 监控安装之cacti
- 配对碱基链(C程序设计进阶第6周)
- 枚举法_寻找三位数
- 欢迎使用CSDN-markdown编辑器
- SQL学习笔记(2)
- tushare
- JVM CMS 常用参数配置
- 进程控制(三)
- C#中判断系统的架构(32位,还是64位)
- 160个CrackMe-1-Acid_burn
- Mysql架构
- Linux Bash 字符串/布尔/文件操作符
- hdoj Surround the Trees 1392 (凸包)
- Easing圆环动画
- sudo tcp_wrappe
- Introduce to algorithm--------pseudo code to C/C++ code (chapter 24)
- 抛弃PHP,WordPress.com以JavaScript重写
- 第五届全国职工技能大赛-计算机程序设计员决赛总结
- Java邮件开发---基本概念
- 从大数据菜鸟走上大师的历程 Scala 第五讲 Array [此博文包含图片]