博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
LeetCode -- Bulls and Cows
阅读量:4695 次
发布时间:2019-06-09

本文共 2524 字,大约阅读时间需要 8 分钟。

Question:

You are playing the following  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 hint. The hint tells your friend how many digits are in the correct positions (called "bulls") and how many digits are in the wrong positions (called "cows"). Your friend will use those hints to find out 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".

 

You may assume that the secret number and your friend's guess only contain digits, and their lengths are always equal.

 

Analysis:

题目描述:你与你的朋友玩“公牛与母牛”的游戏:你写出4位秘密数字,然后让你的朋友猜出它。每次你的朋友给出一组数字,你都要给出一些hint。这些线索能够告诉你的朋友有多少位数字在正确的位置上(“公牛”),和有多少数字在错误的位置上(“母牛”)。你的朋友将会根据你给出的提示找到正确地数字。

例如:

秘密数字是:“1807”

朋友给出的数字是:“7810”

提示是:1个bull和3个cows.(bull是8, cows分别是7、1、0)

 

写一个函数能够根据你和朋友的数字给出hint,用A表示bulls,用B表示cows。在上面的例子中,你的函数应该返回“1A3B”。

请注意:在你给出的秘密数字和朋友给出的猜测中可能出现重复数字。例如:

秘密数字:“1123”

朋友给出的数字:“0111”

在这种情况下,第一个1是bull, 第2 or 3个1是cow,你的函数应该返回“1A1B”。

你可以假设你的秘密数字和朋友给出的仅仅包含数字,并且他们的长度是相等的。

思路:该问题是找出朋友给出的数字中数字和位置都正确的和位置错误的。

首先遍历一遍,在遍历的过程中,记录匹配的正确地个数,同时用两个hashMap记录secret和guess字符串中分别出现的数字及个数,然后在错误匹配中加入较小的值即可。

 

Answer:

import java.util.Map.Entry;public class Solution {  public static String getHint(String secret, String guess) {            int a = 0, b = 0; //分别用来记录A B的数目            char[] secretCh = secret.toCharArray();            char[] guessCh = guess.toCharArray();            HashMap
map1 = new HashMap
(); HashMap
map2 = new HashMap
(); for(int i=0; i
< map2.get(key) ? value : map2.get(key); } } StringBuffer sb = new StringBuffer(); sb.append(Integer.toString(a)); sb.append("A"); sb.append(Integer.toString(b)); sb.append("B"); return sb.toString(); } }

 

转载于:https://www.cnblogs.com/little-YTMM/p/4948485.html

你可能感兴趣的文章
HTTP请求、响应报文格式
查看>>
Android“寄生兽”漏洞技术分析
查看>>
jQuery代码在移动端不运行
查看>>
unbuntu 安装nginx
查看>>
【Oracle】Oracle中复合数据类型
查看>>
秀一下偶的数码奖品
查看>>
C# winform中Show()和ShowDialog()的区别
查看>>
linux uname命令参数及用法详解--linux查看系统信息命令
查看>>
A-Text Reverse(文本反向读)
查看>>
android studio使用部分报错处理
查看>>
Android 自定义ToolBar详细使用
查看>>
psexec局域网执行远程命令
查看>>
H-ui.admin 后台模板学习网
查看>>
解决supervisord启动问题
查看>>
全局组,通用组,本地组
查看>>
wget 抓取页面
查看>>
MYSQL错误代码#1045 Access denied for user 'root'@'localhost'
查看>>
linux 无需主机密码传输文件
查看>>
利用emacs调试C++程序教程
查看>>
VSCode快捷键
查看>>