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

猜你喜欢

转载自www.cnblogs.com/xuanlu/p/12301038.html