Bulls and Cows
来源:互联网 发布:大掌柜软件免费版 编辑:程序博客网 时间:2024/06/12 00:32
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"
.
public String getHint(String secret, String guess) { int acount = 0; int bcount = 0; int[] nums = new int[10]; for(int i = 0 ; i < secret.length();i++) { if(secret.charAt(i)==guess.charAt(i)) acount++; else { if(nums[secret.charAt(i)-'0']++<0)//相当于是hash表 bcount++; if(nums[guess.charAt(i)-'0']-->0) bcount++; } } return acount+"A"+bcount+"B"; }
- [LeetCode]Bulls and Cows
- [LeetCode] Bulls and Cows
- LeetCode Bulls and Cows
- [leetcode299]Bulls and Cows
- Bulls and Cows
- leetcode | Bulls and Cows
- Bulls and Cows
- LeetCode:Bulls and Cows
- LeetCode -- Bulls and Cows
- leetcode: Bulls and Cows
- [leetcode]Bulls and Cows
- Bulls and Cows
- Bulls and Cows
- 299. Bulls and Cows
- Bulls and Cows-LeetCode
- Leetcode191: Bulls and Cows
- [Leetcode]Bulls and Cows
- Bulls and Cows
- POJ 1704 Georgia and Bob 博弈
- Android 编译环境的搭建
- UI高级------多线程(线程与进程)
- Arrays源码分析
- 多功能彩屏ACSII 8*16 ,6*8实用显示程序
- Bulls and Cows
- 【HD 2066】一个人的旅行(dijkstra)
- 毕向东Java视频学习笔记【Day15 字符串+StringBuffer+StringBuilder类基础】
- Spring 系列,第 3 部分: 进入 Spring MVC
- IMX6之emmc的u-boot无法启动调试方法
- 如何让JS变量和字符串拼接后,是变量而不是字符串
- Inkscape - canvas & resize (width/height)
- <hdoj2066>一个人的旅行
- Struts2标签