leetcode-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.
背景介绍:
import java.util.*;
public class BullsAndCows {
public static String getHint(String secret, String guess) {
//自己的思路:用集合做,考虑不全面,不是从问题出发
/*
* int bulls = 0; int cows = 0; List<Character> arr = new ArrayList<>();
* for(int i=0;i<secret.length();i++){ arr.add(secret.charAt(i)); }
* for(int i=0;i<secret.length();i++){ if(secret.charAt(i) ==
* guess.charAt(i)){ bulls ++; arr.set(i,'a'); }else
* if(arr.contains(guess.charAt(i))){ cows ++; } } if(index ==4) return
* "4A0B"; return bulls+"A"+cows+"B"; } public static void main(String[]
* args) { // TODO Auto-generated method stub String a = "01"; String b
* = "11"; System.out.print(getHint(a,b));
*/
// 思路:secret have one char, result plus; guess have one, result reduce.
// 这是用一个数组记录,+1,-1;
/*
* if(secret.length() == 0){return "0A0B";}
*
* int bull = 0; int cow = 0; int [] result = new int [10];
*
* for(int i = 0;i<secret.length();i++) { int x = secret.charAt(i) - 48; //char转成int类型1
* int y = guess.charAt(i) - 48;
*
* if(x == y) { bull++; } else { if(result[x] < 0){cow++;} result[x]++;
* if(result[y] > 0){cow++;} result[y]--; } }
*
* return bull+"A"+cow+"B";
*/
// 最简单的思路:将每位数字的出现次数记录到 数组上!! good idea!!
// 如果对应相等就不用记录,不相等对应数组就 +1,最后取这两个数组相应位置的较小值;
int len = secret.length();
int[] secretarr = new int[10];
int[] guessarr = new int[10];
int bull = 0, cow = 0;
for (int i = 0; i < len; ++i) {
if (secret.charAt(i) == guess.charAt(i)) {
++bull;
} else {
++secretarr[secret.charAt(i) - '0']; //char转成int类型2
++guessarr[guess.charAt(i) - '0'];
}
}
for (int i = 0; i < 10; ++i) {
cow += Math.min(secretarr[i], guessarr[i]);
}
return "" + bull + "A" + cow + "B";
}
}
思考:如何用hash来做?