博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
299. Bulls and Cows
阅读量:2351 次
发布时间:2019-05-10

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

题目

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.

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.

Please note that both secret number and friend’s guess may contain duplicate digits.

Example 1:

Input: secret = “1807”, guess = “7810”

Output: “1A3B”
Explanation: 1 bull and 3 cows. The bull is 8, the cows are 0, 1 and 7.

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

我的想法

关键在于cow的情况下的多个相同元素问题。

用list存储非bull的元素,遇到相同元素cow计数并remove这个元素

class Solution {
public String getHint(String secret, String guess) {
int bull = 0, cow = 0; List
listSect = new ArrayList<>(); List
listGues = new ArrayList<>(); for(int i = 0; i < secret.length(); i++){
if(secret.charAt(i) == guess.charAt(i)) bull++; else {
listSect.add(secret.substring(i,i+1)); listGues.add(guess.substring(i,i+1)); } } for(int i = 0; i < listGues.size(); i++){
if(listSect.contains(listGues.get(i))){
cow++; listSect.remove(listGues.get(i)); } } String res = bull+"A"+cow+"B"; return res; }}

解答

leetcode solution 1:

同一个数组用正数表示secret访问过,负数表示guess访问过。
cow只存在两种情况:secret先访问guess后访问 和 guess先访问secret后访问。如果是第一种情况,则数组为正数,即guess.charAt(i)-'0']-- > 0

public String getHint(String secret, String guess) {
int bulls = 0; int cows = 0; int[] numbers = new int[10]; for (int i = 0; i
0) cows++; } } return bulls + "A" + cows + "B";}

转载地址:http://wbqvb.baihongyu.com/

你可能感兴趣的文章
electron开发
查看>>
NodeJS开发c++扩展模块
查看>>
Electron如何调用NodeJS扩展模块
查看>>
NodeJS通过ffi调用DLL
查看>>
Electron通过ffi调用DLL
查看>>
Node.js & Electron的扩展模块
查看>>
Mysql semi-sync VS group replication, 谁快?
查看>>
Android Looper Message MessageQueue Handler
查看>>
Win10下安装卸载Oracle11g的教程及各种坑
查看>>
Zookeeper
查看>>
更新mysql5.7修改字符集
查看>>
Windows系统护眼色设置
查看>>
JUC多线程&lambda之美&ThreadLocal
查看>>
碎片清理
查看>>
程序员不能错过的技术网站
查看>>
冒泡排序(分析+代码调优)
查看>>
Vue
查看>>
乐优商城总结
查看>>
如何使用Git上传和更新项目至Github
查看>>
选择排序(分析+代码调优)
查看>>