本文主要是介绍leetcode:(299) Bulls and Cows(java),希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
题目:
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.
题目大意:
你正和你的朋友一起玩下面的公牛和母牛游戏:你写下一个数字然后让你的朋友猜猜这个数字是多少。 每当你的朋友做出猜测时,你提供一个提示,表明所述猜测中有多少位数与你的密码完全匹配,包括数字和位置(称为“公牛”)以及有多少位数与秘密号码相匹配但位于错误的位置 (称为“奶牛”)。 您的朋友将使用连续的猜测和提示最终得出密码。
根据秘密号和朋友的猜测写一个函数来返回提示,用A表示公牛,用B表示奶牛。
请注意,密码和朋友的猜测都可能包含重复的数字。
代码及解题思路如下:
package LeetCode_HashTable;public class GetHint_299_1022 {public String GetHint(String secret, String guess) {int bulls = 0;//记录公牛的个数int cows = 0;//记录母牛的个数int length = secret.length();int[] nums = new int[10];//创建一个长度为10的数组,用来存放0-9出现的次数for (int i = 0; i < length; i++) {int s = Character.getNumericValue(secret.charAt(i));int g = Character.getNumericValue(guess.charAt(i));if (s == g) { bulls++;//如果在位置i处,s和g相等,那么bulls++} else {if (nums[s] < 0) {cows++; //如果在i处s和g不相等,并且s在已经出现过在g中的其他位置,cows++}if (nums[g] > 0) {cows++; //如果在i处s和g不相等,并且g已经出现过在s中的其他位置,cows++}nums[s]++;nums[g]--;}}return bulls + "A" + cows + "B";}public static void main(String[] args) {String s = "1807";String g = "7810";GetHint_299_1022 test = new GetHint_299_1022();String result = test.GetHint(s, g);System.out.println(result);} }
这篇关于leetcode:(299) Bulls and Cows(java)的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!