Bulls and Cows 1807 7810 return "1A3B"

来源:互联网 发布:陈秋平网络大电影 编辑:程序博客网 时间:2024/04/29 17:52

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 are0,1 and7.)

Write a function to return a hint according to the secret number and friend's guess, useA to indicate the bulls andB 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.

 

public class Solution {
    public String getHint(String secret, String guess) {
        int[] countB=new int[10];//定义了一个长度为10的数组,因为整数为10个数字
        int A=0;
        int B=0;
        if(secret.length()!=guess.length()){
            System.out.println("Please ensure the two inputs have equal length!");
            System.exit(0);//程序正常退出
        }

        else{//下边共同维护这个长度为10的数组
            for(int i=0;i<secret.length();i++) {
                if(secret.charAt(i)==guess.charAt(i))//charAt()功能类似于数组,可以把字符串看作是char类型的数组,它是把字符串拆分获取其中的某个字符;返回指定位置的字符。
                    A++;
                else{
                    countB[secret.charAt(i)-'0']++;
                    if(countB[secret.charAt(i)-'0']<=0)
                        B++;//如果<=0.表示这个数字在guess里边出现过,因为secret只是负责加
                    countB[guess.charAt(i)-'0']--;
                    if(countB[guess.charAt(i)-'0']>=0)
                        B++;//如果>=0.表示这个数字在secret里边出现过,因为guess只是负责减
                }
            }
        }
        return String.valueOf(A)+"A"+String.valueOf(B)+"B";//String.valueOf()把整数转换为String
    }
}

 

0 0
原创粉丝点击