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

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

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.

 

Solution:

1 public class Solution { 2     public String getHint(String secret, String guess) { 3         int bulls = 0; 4         int cows = 0; 5         int[] nums = new int[10]; 6         for(int i = 0; i < secret.length(); ++i) { 7             if(secret.charAt(i) == guess.charAt(i)) 8                 bulls++; 9             else {10                 if(nums[secret.charAt(i) - '0'] < 0)11                     cows++;12                 if(nums[guess.charAt(i) - '0'] > 0)13                     cows++;14                 nums[secret.charAt(i) - '0']++;15                 nums[guess.charAt(i) - '0']--;16             }17         }18         return bulls + "A" + cows + "B";19     }20 }

 

转载于:https://www.cnblogs.com/Phoebe815/p/4932098.html

你可能感兴趣的文章
浅谈Sql各种join的用法
查看>>
Durid数据库连接池配置(不使用框架)
查看>>
BarCode128B字符转换函数(PB,SQL)
查看>>
watir学习资料
查看>>
Jmeter属性和变量
查看>>
java并发编程:并发容器之CopyOnWriteArrayList(转)
查看>>
python基础——面向对象进阶下
查看>>
Linux vi 命令详解
查看>>
本地如何搭建IPv6环境测试你的APP
查看>>
oracle、mysql新增字段,字段存在则不处理
查看>>
C++ NULL与nullptr的区别
查看>>
Discretized Streams, 离散化的流数据处理
查看>>
Spark源码分析 – SchedulerBackend
查看>>
黑马程序员 Java输入\输出
查看>>
python字符串处理
查看>>
live555学习笔记4-计划任务(TaskScheduler)深入探讨
查看>>
【Unity3D】获取鼠标在三维空间(世界坐标系)的位置
查看>>
Python虚拟机函数机制之名字空间(二)
查看>>
线段树
查看>>
SharePoint2010联合搜索——Google、百度
查看>>