leetcode:(299) Bulls and Cows(java)

题目:

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.

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. 

Please note that both secret number and friend's guess may contain duplicate digits.

题目大意:

你正和你的朋友一起玩下面的公牛和母牛游戏:你写下一个数字然后让你的朋友猜猜这个数字是多少。 每当你的朋友做出猜测时,你提供一个提示,表明所述猜测中有多少位数与你的密码完全匹配,包括数字和位置(称为“公牛”)以及有多少位数与秘密号码相匹配但位于错误的位置 (称为“奶牛”)。 您的朋友将使用连续的猜测和提示最终得出密码。

根据秘密号和朋友的猜测写一个函数来返回提示,用A表示公牛,用B表示奶牛。

请注意,密码和朋友的猜测都可能包含重复的数字。

代码及解题思路如下:

package LeetCode_HashTable;

public class GetHint_299_1022 {
    public String GetHint(String secret, String guess) {
        int bulls = 0;//记录公牛的个数
        int cows = 0;//记录母牛的个数

        int length = secret.length();
        int[] nums = new int[10];//创建一个长度为10的数组,用来存放0-9出现的次数

        for (int i = 0; i < length; i++) {
            int s = Character.getNumericValue(secret.charAt(i));
            int g = Character.getNumericValue(guess.charAt(i));

            if (s == g) { 
                bulls++;//如果在位置i处,s和g相等,那么bulls++
            } else {
                if (nums[s] < 0) {
                    cows++; //如果在i处s和g不相等,并且s在已经出现过在g中的其他位置,cows++
                }
                if (nums[g] > 0) {
                    cows++; //如果在i处s和g不相等,并且g已经出现过在s中的其他位置,cows++
                }
                nums[s]++;
                nums[g]--;
            }
        }
        return bulls + "A" + cows + "B";
    }

    public static void main(String[] args) {
        String s = "1807";
        String g = "7810";

        GetHint_299_1022 test = new GetHint_299_1022();
        String result = test.GetHint(s, g);
        System.out.println(result);
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值