LeetCode--299. Bulls and Cows

来源:互联网 发布:淘宝闲鱼怎么交易流程 编辑:程序博客网 时间:2024/05/17 22:59

Problem:

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 examp:Secret number:  "1123" Friend's guess: "0111" 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.

Analysis:
题目意思:
你和朋友在玩下面的猜数字游戏(Bulls and Cows):你写下一个4位数的神秘数字然后让朋友来猜,你的朋友每次猜一个数字,你给一个提示,告诉他有多少个数字处在正确的位置上(称为”bulls” 公牛),以及有多少个数字处在错误的位置上(称为”cows” 奶牛),你的朋友使用这些提示找出那个神秘数字。

分析:这个题可以利用两次遍历完成,但是利用hash的方法可以遍历一次完成。在遍历的时候,如果当前这两个数相等,则bulls加一,如果不相等,则进行判断当前数字g之前有没有在前面的s中出现。利用s增,g减的方式来表示s出现的次数和g出现的次数。
Answer:
容易想到的两个存放secret和guess 的数组,统计之后比较1-10的最小个数:

public class Solution {    public String getHint(String secret, String guess) {        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'];                ++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方法:

public class Solution {    public String getHint(String secret, String guess) {        int[] hash = new int[10];        int Acount=0,Bcount=0;        for(int i=0;i<secret.length();i++){            int s = secret.charAt(i)-'0';            int g = guess.charAt(i)-'0';            if(s==g) Acount++;            else{                if(hash[g]>0) Bcount++;//s在g之前出现过                if(hash[s]<0) Bcount++;//g在s之前出现过                hash[g]--;//缺一个和g匹配的                hash[s]++;//s多一个匹配的            }        }        return Acount+"A"+Bcount+"B";        //注意这样写不可以:return Acount+'A'+Bcount+'B';    }}
0 0
原创粉丝点击