[LeetCode] Bulls and Cows

简介: This problem seems to be easy at the first glance, especially the problem gives a too much simpler example.

This problem seems to be easy at the first glance, especially the problem gives a too much simpler example. Make sure you understand the problem by making more examples or refering to some other material, like the Wikipedia article.

Stefan shares a very simple and elegant solution, which is rewritten below using multiset in C++.

 1 class Solution {
 2 public:
 3     string getHint(string secret, string guess) {
 4         int bull = 0, both = 0, n = secret.length();
 5         for (int i = 0; i < n; i++)
 6             bull += (secret[i] == guess[i]);
 7         for (char c = '0'; c <= '9'; c++)
 8             both += min(count(secret.begin(), secret.end(), c), 
 9                         count(guess.begin(), guess.end(), c));
10         return to_string(bull) + "A" + to_string(both - bull) + "B";
11     }
12 };

 

目录
相关文章
LeetCode 299. Bulls and Cows
你正在和你的朋友玩 猜数字(Bulls and Cows)游戏:你写下一个数字让你的朋友猜。每次他猜测后,你给他一个提示,告诉他有多少位数字和确切位置都猜对了(称为“Bulls”, 公牛),有多少位数字猜对了但是位置不对(称为“Cows”, 奶牛)。你的朋友将会根据提示继续猜,直到猜出秘密数字。 请写出一个根据秘密数字和朋友的猜测数返回提示的函数,用 A 表示公牛,用 B 表示奶牛。
88 0
LeetCode 299. Bulls and Cows
[LeetCode]--299. Bulls and Cows
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
1143 0
LeetCode 299 Bulls and Cows(公牛和母牛)(HashMap)
版权声明:转载请联系本人,感谢配合!本站地址:http://blog.csdn.net/nomasp https://blog.csdn.net/NoMasp/article/details/52560310 翻译 你在和朋友们玩一个叫做“公牛和母牛”的游戏:你写下一组数字,然后让你的朋友来猜它。
1057 0
[LeetCode] Bulls and Cows
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 hin
1130 0
|
28天前
|
Unix Shell Linux
LeetCode刷题 Shell编程四则 | 194. 转置文件 192. 统计词频 193. 有效电话号码 195. 第十行
本文提供了几个Linux shell脚本编程问题的解决方案,包括转置文件内容、统计词频、验证有效电话号码和提取文件的第十行,每个问题都给出了至少一种实现方法。
LeetCode刷题 Shell编程四则 | 194. 转置文件 192. 统计词频 193. 有效电话号码 195. 第十行
|
2月前
|
Python
【Leetcode刷题Python】剑指 Offer 32 - III. 从上到下打印二叉树 III
本文介绍了两种Python实现方法,用于按照之字形顺序打印二叉树的层次遍历结果,实现了在奇数层正序、偶数层反序打印节点的功能。
50 6
|
2月前
|
搜索推荐 索引 Python
【Leetcode刷题Python】牛客. 数组中未出现的最小正整数
本文介绍了牛客网题目"数组中未出现的最小正整数"的解法,提供了一种满足O(n)时间复杂度和O(1)空间复杂度要求的原地排序算法,并给出了Python实现代码。
99 2
|
28天前
|
数据采集 负载均衡 安全
LeetCode刷题 多线程编程九则 | 1188. 设计有限阻塞队列 1242. 多线程网页爬虫 1279. 红绿灯路口
本文提供了多个多线程编程问题的解决方案,包括设计有限阻塞队列、多线程网页爬虫、红绿灯路口等,每个问题都给出了至少一种实现方法,涵盖了互斥锁、条件变量、信号量等线程同步机制的使用。
LeetCode刷题 多线程编程九则 | 1188. 设计有限阻塞队列 1242. 多线程网页爬虫 1279. 红绿灯路口