一、题目名称java
Bulls and Cows(猜数字游戏)git
二、题目地址数组
https://leetcode.com/problems/bulls-and-cows/code
三、题目内容游戏
英文:You are playing the following Bulls and Cows 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.leetcode
中文:假设你正在玩猜数字游戏(Bulls and Cows):你写出4个数字让你的朋友猜,每次你的朋友猜一个数字,你给出一条线索,这个线索告诉你的朋友,有多少个数字位置是正确的(被称为Bulls),有多少个数字位置是不正确的(被称为Cows),你的朋友须要根据这些线索最终猜出正确的数字。开发
例如,给出的数字是1807,你的朋友猜的是7810,这里用A表明Bulls,B表明Cows,则给出的线索是1A3B。get
题目中给出的secret(被猜想数字)和guess(猜想的数字)长度必定是同样的。it
四、解题方法1io
作这道题还须要注意,通常的猜数字游戏中,被猜的数字有四个且互不相同,但在本题中,能够有任意多个数字,且数字有可能存在同一数字重复屡次出现的状况。
一开始我想了一个比较笨的办法,即分别求出A和B的数量,暴力破解,Java代码以下:
/** * @功能说明:LeetCode 299 - Bulls and Cows * @开发人员:Tsybius2014 * @开发时间:2015年10月31日 */ public class Solution { /** * 猜数字 * @param secret 原数字 * @param guess 猜想数字 * @return */ public String getHint(String secret, String guess) { if (secret == null || guess == null || secret.length() != guess.length()) { return ""; } int countA = 0; int countB = 0; char[] arrA = secret.toCharArray(); char[] arrB = guess.toCharArray(); //求A的数量 for (int i = 0; i < arrA.length; i++) { for (int j = 0; j < arrB.length; j++) { if (arrA[i] == ' ' || arrB[j] == ' ') { continue; } else if (arrA[i] == arrB[j]) { if (i == j) { countA++; arrA[i] = ' '; arrB[j] = ' '; } } } } //求B的数量 for (int i = 0; i < arrA.length; i++) { for (int j = 0; j < arrB.length; j++) { if (arrA[i] == ' ' || arrB[j] == ' ') { continue; } else if (arrA[i] == arrB[j]) { countB++; arrA[i] = ' '; arrB[j] = ' '; } } } return String.valueOf(countA) + "A" + String.valueOf(countB) + "B"; } }
五、解题方法2
后来我看了下讨论区,发现了一种更加高效的方法。这个方法的大体思路是,建立一个包含10个元素的数组,分别用于记录遇到的每一个数字的状况。这个方法只须要遍历一次数组。
Java代码以下:
/** * @功能说明:LeetCode 299 - Bulls and Cows * @开发人员:Tsybius2014 * @开发时间:2015年10月31日 */ public class Solution { /** * 猜数字 * @param secret 原数字 * @param guess 猜想数字 * @return */ public String getHint(String secret, String guess) { if (secret == null || guess == null || secret.length() != guess.length()) { return ""; } int countA = 0; int countB = 0; int[] count = new int[10]; for (int i = 0; i < secret.length(); i++) { if (secret.charAt(i) == guess.charAt(i)) { countA++; } else { count[secret.charAt(i) - '0']++; if (count[secret.charAt(i) - '0'] <= 0) { countB++; } count[guess.charAt(i)- '0']--; if (count[guess.charAt(i)- '0'] >= 0) { countB++; } } } return String.valueOf(countA) + "A" + String.valueOf(countB) + "B"; } }
END