[LC] 299. Bulls and Cows

Posted xuanlu

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了[LC] 299. Bulls and Cows相关的知识,希望对你有一定的参考价值。

Example 1:

Input: secret = "1807", guess = "7810"

Output: "1A3B"

Explanation: 1 bull and 3 cows. The bull is 8, the cows are 0, 1 and 7.

Example 2:

Input: secret = "1123", guess = "0111"

Output: "1A1B"

Explanation: The 1st 1 in friend‘s guess is a bull, the 2nd or 3rd 1 is a cow.
class Solution {
    public String getHint(String secret, String guess) {
        int[] nums = new int[10];
        int len = secret.length();
        int bulls = 0;
        int cows = 0;
        for (int i = 0; i < len; i++) {
            char sWord = secret.charAt(i);
            char gWord = guess.charAt(i);
            if (sWord == gWord) {
                bulls += 1;
            } else {
                if (nums[gWord - ‘0‘] > 0) {
                    cows += 1;
                }
                if (nums[sWord - ‘0‘] < 0) {
                    cows += 1;
                }
                nums[sWord - ‘0‘] += 1;
                nums[gWord - ‘0‘] -= 1;
            }
        }
        return bulls + "A" + cows + "B";
    }
}

 

以上是关于[LC] 299. Bulls and Cows的主要内容,如果未能解决你的问题,请参考以下文章

299. Bulls and Cows

Leetcode 299:Bulls and Cows

leetcode [299]Bulls and Cows

[LeetCode299]Bulls and Cows

LeetCode_299. Bulls and Cows

[leetcode-299-Bulls and Cows]