leetcode [#299]

目录

题目

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.

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”.

Note:
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.


解决方案

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

注意事项

  1. 如果对应位字符相同,则bull加一。
  2. 如果不同,使用一个长度为10的数组(0-9是10个数字)来分析secret和guess中数字字符的情况。数组各元素初始化为0。
    secret和guess的当前位不同,在数组numbers中,以secret所代表数字为下标的元素如果小于零,那么说明有一个cow出现,cows++,判断完成后,给numbers数组当前位加一;以guess所代表数字为下标的元素如果大于零,那么说明有一个cow出现,cows++,判断完成后,给numbers数组当前位减一。
  3. 数组的作用是:如果数组中secret当前字符对应数字为下标的元素小于零,说明在这之前的操作中,guess中出现过若干次这个数字(这样才会被减了若干个1,才会导致小于零),且肯定是在其他位置上(不会与secret当前字符对应数字所代表下标一样),那么就符合了“cow”的要求—值相同,位置不同。这样统计一次(cows++)后,将对应数组元素加一,抵消掉这次的作用,接下来继续统计。同理,如果数组中guess当前字符对应数字为下标的元素大于零,说明在这之前的操作中,secret中出现过若干次这个数字(这样才会被加了若干个1,才会导致大于零),且肯定是在其他位置上(不会与guess当前字符对应数字所代表下标一样),那么也就符合了“cow”的要求—值相同,位置不同。这样统计一次(cows++)后,将对应数组元素减一,抵消掉这次的作用,接下来继续统计。