LeetCode 299. Bulls and Cows(公牛和母牛)
来源:互联网 发布:网站推广软件skycc 编辑:程序博客网 时间:2024/05/20 12:24
原题网址:https://leetcode.com/problems/bulls-and-cows/
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"
.You may assume that the secret number and your friend's guess only contain digits, and their lengths are always equal.
方法:统计各个数字的个数,然后比较。
public class Solution { public String getHint(String secret, String guess) { char[] sa = secret.toCharArray(); char[] ga = guess.toCharArray(); int len = sa.length; int pos = 0; int bulls = 0; while (pos < len) { if (sa[pos] == ga[pos]) { bulls ++; sa[pos] = sa[len-1]; ga[pos] = ga[len-1]; len --; } else { pos ++; } } int[] sd = new int[10]; int[] gd = new int[10]; for(int i=0; i<len; i++) { sd[sa[i]-'0'] ++; gd[ga[i]-'0'] ++; } int bows = 0; for(int i=0; i<10; i++) bows += Math.min(sd[i], gd[i]); return bulls+"A"+bows+"B"; }}
- LeetCode 299. Bulls and Cows(公牛和母牛)
- LeetCode 299 Bulls and Cows(公牛和母牛)(HashMap)
- Leetcode:299. Bulls and Cows(JAVA)
- [leetcode] 299. Bulls and Cows
- LeetCode || 299. Bulls and Cows
- LeetCode 299. Bulls and Cows
- Leetcode 299. Bulls and Cows
- LeetCode.299.Bulls and Cows
- LeetCode--299. Bulls and Cows
- 【LeetCode】299. Bulls and Cows
- [leetcode] 299. Bulls and Cows
- LeetCode *** 299. Bulls and Cows
- leetcode 299. Bulls and Cows
- LeetCode 299. Bulls and Cows
- LeetCode-299.Bulls and Cows
- Leetcode 299. Bulls and Cows
- 299.[leetcode]Bulls and Cows
- leetcode 299. Bulls and Cows
- 栈的链表表示
- opnet14.5 tutorial翻译——包交换网络仿真
- 【异或+贪心】HDU5661Claris and XOR【BestCoder Round #79 (div.2)】
- [学习笔记]php数据库访问抽象层PDO 1
- StringBuilder StringBuffer
- LeetCode 299. Bulls and Cows(公牛和母牛)
- 【补充】过程是什么?
- Android学习笔记(动画)
- Leetcode no. 169
- hadoop平台搭建(4)--伪分布式的配置及运行
- 上周工作中遇到的问题以及解决方法总结
- Android-->圆角图片,圆角任意View,圆角父布局Layout(任意形状的View且超简洁实现)
- android:Widget.Material.Button.Colored找不到
- 顺时针打印矩阵