【哈希表】LeetCode 299. 猜数字游戏

题目链接

299. 猜数字游戏

思路

建立两个哈希表分别存储 secretguess 中不是bulls的数字出现次数。

代码

class Solution{
    public String getHint(String secret, String guess){
        int[] secretAlphaNumber = new int[10];
        int[] guessAlphaNumber = new int[10];
        int bulls = 0;
        int cows = 0;

        for(int i = 0; i < secret.length(); i++){
            if(secret.charAt(i) == guess.charAt(i)){
                bulls++;
            }else{
                secretAlphaNumber[secret.charAt(i) - '0']++;
                guessAlphaNumber[guess.charAt(i) - '0']++;
            }
        }

        for(int i = 0; i < 10; i++){
            cows += Math.min(secretAlphaNumber[i], guessAlphaNumber[i]);
        }

        return bulls + "A" + cows + "B";
    }
}
posted @ 2023-01-07 14:45  Frodo1124  阅读(30)  评论(0编辑  收藏  举报