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:

Secret number:  "1807"
Friend's guess: "7810"

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

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".

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 1 in friend's guess is a bull, the 2nd or 3rd 1 is 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 = ;
vector<bool> solved(secret.size(), false);
for(int i = ; i < secret.size(); ++i){
++hash[secret[i]];
}
for(int i = ; i < secret.size(); ++i){
if(secret[i] == guess[i]){
countA++;
solved[i] = true;
--hash[secret[i]];
}
}
for(int i = ; i < guess.size(); ++i){
if(!solved[i] && hash[guess[i]] > ){
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;
}
};

最新文章

  1. CSS基础3
  2. contiki在keil下的stm32平台移植
  3. 20145334 《Java程序设计》第10周学习总结
  4. IT公司笔试题(一)
  5. The Secrets of Oracle Row Chaining and Migration
  6. JDE910笔记1--基础介绍及配置
  7. Ubuntu下MySQL数据库安装与配置与卸载
  8. SOCKS5协议
  9. 【HDOJ】4605 Magic Ball Game
  10. 新浪新闻API接口
  11. BZOJ 1797: [Ahoi2009]Mincut 最小割( 网络流 )
  12. 电子产品使用感受之——我的Mac只有256GB,我的照片库该怎么办?
  13. spring(AOP)静态代理
  14. Mac下Tomcat安装与Intellij IDEA配置Tomcat
  15. linux学习:【第2篇】常用命令
  16. Servlet拓展
  17. jscript调用bat注意事项
  18. [Issue]git做rebase时,弹出编辑器为nano,不会使用
  19. 目标跟踪之meanshift---meanshift2
  20. redis分布式集群3种架构方案

热门文章

  1. 647. Palindromic Substrings(马拉车算法)
  2. JAVA面试题整理(1)-基础
  3. feather mac 问题小结
  4. 20145303刘俊谦 《Java程序设计》实验四 实验报告
  5. Kali视频学习6-10
  6. strcpy、sprintf、memcpy的区别
  7. wechat4j获取用户昵称乱码修复
  8. 数据结构实习 problem O Huffman Tree
  9. [小问题笔记(十一)] SQL SERVER 将可空字段改为 NOT NULL不可为空的两个方法
  10. [小问题笔记(五)] 用SQL加密字符串(MD5、SHA1),顺便解决读取数据加密后不一样的问题