Easy-题目48:299. 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.
题目大意:
你在和朋友玩Bulls and Cows游戏:你写出一串数字,然后你的朋友猜这个数字,如果数位和数字完全对应,则称为bulls(用A表示),如果数字正确而数位错误,则称为cows(用B表示)。
输入你的答案和朋友的猜测,判断有几个bulls和几个cows(用xAyB)表示。
例如答案=1807,猜测=7810,则数位8正确,1,0,7数字正确但位置错误,所以输出1A3B。
题目分析:
使用scount和gcount两个二位数组统计各数字所在的下标,s和g两个数组记录每个数字出现了多少次,然后从0到9全部遍历,先看s[i]和g[i],即数字i在两个串中分别出现了多少次,取较小值,先全部加到B上,再扫scount[i]和gcount[i]数组去比较i出现的数位,如果找到了相同数位,则b递减a递增,直到扫完10个数字。时间复杂度和空间复杂度都是O(n)。
源码:(language:java)

public class Solution {
    public String getHint(String secret, String guess) {
        int slen=secret.length();
        boolean[][] scount=new boolean[10][slen];
        boolean[][] gcount=new boolean[10][slen];
        int[] s=new int[10];
        int[] g=new int[10];
        int a = 0,b = 0;
        for(int i=0;i<slen;i++) {
            scount[secret.charAt(i)-'0'][i]=true;
            s[secret.charAt(i)-'0']++;
            gcount[guess.charAt(i)-'0'][i]=true;
            g[guess.charAt(i)-'0']++;
        }
        for(int i=0;i<10;i++) {
            int binc=Math.min(s[i], g[i]);  
            if(binc==0)
                continue;
            b+=binc;
            for(int j=0;j<slen;j++) {
                if(scount[i][j] && gcount[i][j]) {
                    b--;
                    a++;
                }
            }
        }
        return new String(a+"A"+b+"B");
    }
}

成绩:
8ms,beats 39.5%,众数4ms,21.65%
cmershen的碎碎念:
这个游戏小时候在电子词典上都玩过,当时做的限定比较多,要求只能是4位数,数字不重复,且当年最大的吐槽是为何只能猜八次。希望以后可以设计一个ai算法解决任意4位猜数字问题。

你可能感兴趣的:(Easy-题目48:299. Bulls and Cows)