首页 > 其他分享 >【哈希表】LeetCode 299. 猜数字游戏

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

时间:2023-01-07 14:57:16浏览次数:70  
标签:guess charAt int bulls ++ secret 哈希 299 LeetCode

题目链接

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";
    }
}

标签:guess,charAt,int,bulls,++,secret,哈希,299,LeetCode
From: https://www.cnblogs.com/shixuanliu/p/17032621.html

相关文章