Wednesday, November 11, 2015

Bulls and Cows

Q:
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 01 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.

A:
 就是简单的对比,数即可(首先数出完全匹配的)再用HashMap,找到所有的secret中出现的 。 再便利guess,确认即可

public class Solution {
    public String getHint(String secret, String guess) {
        int A = 0,AB =0;
        Map<Character,Integer> map = new HashMap();
        for(int i =0;i<secret.length();i++){
            char ch1 = secret.charAt(i);
            if( ch1==guess.charAt(i))
                A++;
            if(map.containsKey(ch1)){
                map.put(ch1,map.get(ch1)+1);
            }else{
                map.put(ch1,1);
            }
        }
        // check guess string for new 
        for(int i =0;i<secret.length();i++){
            char ch = guess.charAt(i);
            if(map.containsKey(ch)){
                AB++;
                map.put(ch,map.get(ch)-1);
                if(map.get(ch)==0)
                    map.remove(ch);
            }
        }
        return ""+A+"A"+(AB-A)+"B";
    }
}



*************************利用0-9这个特性,创建2个数组*****************

public class Solution {
    public String getHint(String secret, String guess) {
        int A = 0, AB=0;
        int C1[] = new int[10];
        int C2[] = new int[10];
        for(int i =0;i<secret.length();i++){
            char ch1 = secret.charAt(i);
            char ch2 = guess.charAt(i);
            if(ch1==ch2)
                A++;
            C1[ch1-'0']++;
            C2[ch2-'0']++;
        }
        for(int i =0;i<10;i++)
            AB+= Math.min(C1[i],C2[i]);
        return ""+A+"A"+(AB-A)+"B";
    }
}












No comments:

Post a Comment