当前位置:网站首页>LeetCode_299_猜数字游戏
LeetCode_299_猜数字游戏
2022-08-04 12:46:00 【Fitz1318】
题目链接
题目描述
你在和朋友一起玩 猜数字(Bulls and Cows)
游戏,该游戏规则如下:
写出一个秘密数字,并请朋友猜这个数字是多少。朋友每猜测一次,你就会给他一个包含下述信息的提示:
- 猜测数字中有多少位属于数字和确切位置都猜对了(称为 “Bulls”,公牛),
- 有多少位属于数字猜对了但是位置不对(称为 “Cows”,奶牛)。也就是说,这次猜测中有多少位非公牛数字可以通过重新排列转换成公牛数字。
给你一个秘密数字 secret
和朋友猜测的数字 guess
,请你返回对朋友这次猜测的提示。
提示的格式为 “xAyB
” ,x
是公牛个数, y
是奶牛个数,A
表示公牛,B
表示奶牛。
请注意秘密数字和朋友猜测的数字都可能含有重复数字。
示例 1:
输入:secret = "1807", guess = "7810"
输出:"1A3B"
解释:数字和位置都对(公牛)用 '|' 连接,数字猜对位置不对(奶牛)的采用斜体加粗标识。
"1807"
|
"7810"
示例 2:
输入:secret = "1123", guess = "0111"
输出:"1A1B"
解释:数字和位置都对(公牛)用 '|' 连接,数字猜对位置不对(奶牛)的采用斜体加粗标识。
"1123" "1123"
| or |
"0111" "0111"
注意,两个不匹配的 1 中,只有一个会算作奶牛(数字猜对位置不对)。通过重新排列非公牛数字,其中仅有一个 1 可以成为公牛数字。
提示:
1 <= secret.length, guess.length <= 1000
secret.length == guess.length
secret
和guess
仅由数字组成
解题思路
遍历+统计
- 对于公牛,需要数字和位置都一样,只要遍历secret和guess,找到
secret.charAt(i) == guess.charAt(i)
的数量即可 - 对于奶牛,只需要统计sercet和guess中各个字符出现的次数,然后取相同字符的最小值累加,然后再减去公牛的数量即可
AC代码
class Solution {
public String getHint(String secret, String guess) {
int len = secret.length();
int correct = 0;
int justSame = 0;
int[] recordS = new int[10];
int[] recordG = new int[10];
for (int i = 0; i < len; i++) {
char s = secret.charAt(i);
char g = guess.charAt(i);
if (s == g) {
correct++;
}
recordS[s - '0']++;
recordG[g - '0']++;
}
justSame += Math.min(recordS[0], recordG[0]);
for (int i = 1; i <= 9; i++) {
justSame += Math.min(recordS[i], recordG[i]);
}
return correct + "A" + (justSame - correct) + "B";
}
}
边栏推荐
猜你喜欢
Valentine's Day Romantic 3D Photo Wall [with source code]
1314元的七夕礼盒,收割了多少直男?
Why is Luo Zhenyu's A-share dream so difficult to fulfill?
【PHP实现微信公众平台开发—基础篇】第1章 课程介绍
rpm安装提示error: XXX: not an rpm package (or package manifest):
ShanDong Multi-University Training #4 A、B、C、G
什么是 DevOps?看这一篇就够了!
Neck modules of the yolo series
num_workers
MATLAB——图像分块
随机推荐
MATLAB——图像分块
Analysis and comparison of mobile cross-end technical solutions
What is DevOps?Enough to read this one!
break与continue超详解!!!
【黑马早报】尚乘数科上市13天,市值超阿里;北大终止陈春花聘用合同;新东方花近200亿退学费和遣散费;张小泉75%产品贴牌代工...
石子 无限拿
Small program on how to play in the construction of e-government service platform value
SSRF-服务器端请求伪造-相关知识
WPF---Grid布局讲解
num_workers
Programmer Qixi Gift - How to quickly build an exclusive chat room for your girlfriend in 30 minutes
数据中台建设(九):数据中台资产运营机制
A Collection of Flutter Tutorials (2022 Edition)
ReentrantLock 原理
技术分享| 小程序实现音视频通话
程序猿七夕礼物-如何30分钟给女友快速搭建专属语聊房
用VbScript控制光驱
"Lonely Walking on the Moon" is a powerful medicine, it can't cure the internal friction of happy twist
【VSCode】一文详解vscode下安装vim后无法使用Ctrl+CV复制粘贴 使用Vim插件的配置记录
永磁同步电机FOC驱动代码讲解