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 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 0
, 1
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"
.
You may assume that the secret number and your friend's guess only contain digits, and their lengths are always equal.
猜数字,完全猜对一位为A,猜对数字但位置不对为B,统计多少个A和B。
map维护一下就行了,没什么含量。
class Solution {
public:
string getHint(string secret, string guess) {
int A = 0, B = 0;
unordered_map<char, int> mp, mp2;
for(int i = 0; i < secret.size(); i++)
{
if(secret[i] == guess[i]) A++;
else
{
mp[secret[i]]++;
mp2[guess[i]]++;
}
}
for(auto k : mp) B += min(k.second, mp2[k.first]);
return to_string(A) + "A" + to_string(B) + "B";
}
};
- JavaScript 教程
- JavaScript 编辑工具
- JavaScript 与HTML
- JavaScript 与Java
- JavaScript 数据结构
- JavaScript 基本数据类型
- JavaScript 特殊数据类型
- JavaScript 运算符
- JavaScript typeof 运算符
- JavaScript 表达式
- JavaScript 类型转换
- JavaScript 基本语法
- JavaScript 注释
- Javascript 基本处理流程
- Javascript 选择结构
- Javascript if 语句
- Javascript if 语句的嵌套
- Javascript switch 语句
- Javascript 循环结构
- Javascript 循环结构实例
- Javascript 跳转语句
- Javascript 控制语句总结
- Javascript 函数介绍
- Javascript 函数的定义
- Javascript 函数调用
- Javascript 几种特殊的函数
- JavaScript 内置函数简介
- Javascript eval() 函数
- Javascript isFinite() 函数
- Javascript isNaN() 函数
- parseInt() 与 parseFloat()
- escape() 与 unescape()
- Javascript 字符串介绍
- Javascript length属性
- javascript 字符串函数
- Javascript 日期对象简介
- Javascript 日期对象用途
- Date 对象属性和方法
- Javascript 数组是什么
- Javascript 创建数组
- Javascript 数组赋值与取值
- Javascript 数组属性和方法
- Python笔记
- JavaScript 技术篇-chrome利用ClipboardEvent写入剪切板,没成功的你就差一步
- 搭建一个高可用负载均衡的集群架构(第三部分)
- C语言学习笔记
- JavaScript 技术篇-js获取窗口标题名,获取页面URL地址
- Pyhon海龟绘制木叶村徽章
- MIT大神写给女神的Q版Python画图库—Cutecharts【技术创作101训练营】
- JavaScript 技术篇-js创建dom节点,并设置属性
- 容器中的数据管理
- Java基础 方法
- Python 技术篇-pyperclip库实现读取写入剪切板,超简单
- 基于consul的Docker-overlay跨多宿主机容器网络
- Python 微信机器人-向指定名称的好友发送微信消息
- JavaScript技术篇-js提升网页视频播放速率,提高慕课网视频播放速度
- 使用docker五步搭建ELK日志收集分析系统