Bulls and Cows

https://leetcode.com/problems/bulls-and-cows/description/

You are playing the followingBulls and Cowsgame 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.

For example:

Secret number:  "1807"
Friend's guess: "7810"

Write a function to return a hint according to the secret number and friend's guess, useAto indicate the bulls andBto indicate the cows. In the above example, your function should return"1A3B".

Please note that both secret number and friend's guess may contain duplicate digits, for example:

Secret number:  "1123"
Friend's guess: "0111"

In this case, the 1st

1

in friend's guess is a bull, the 2nd or 3rd

1

is a cow, and your function should return

"1A1B"

You may assume that the secret number and your friend's guess only contain digits, and their lengths are always equal.

Thoughts

bulls数目好树,麻烦的是cows。cows本质是算除去bulls后的secret中包含了多少个guess中的字符。这让我想到了在滑动窗口中常用的数是否数目一致的amount map.

Code

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

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

        for (int i = 0; i < guess.length(); i++) {
            if (secret.charAt(i) != guess.charAt(i)) {
                Character c = guess.charAt(i);
                amount[c - '0']--;
                if (amount[c - '0'] >= 0) {
                    cows++;
                }
            }
        }
        return bulls + "A" + cows + "B";
    }
}

Analysis

时间复杂度O(n), 空间O(1)

Ver.2

还可以把两个循环合并。对于先在guess中出现后在secret中出现的,相当于guess先被减到负值,然后遇到secret中对应元素再把它往正数加。加到0代表当前刚好guess和secret中该元素数目相等。加到正代表guess中欠缺。

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

        for (int i = 0; i < guess.length(); i++) {
            if (secret.charAt(i) != guess.charAt(i)) {
                Character c = guess.charAt(i), t = secret.charAt(i);
                amount[t - '0']++;
                if (amount[t - '0'] <= 0) {
                    cows++;
                }
                amount[c - '0']--;
                if (amount[c - '0'] >= 0) {
                    cows++;
                }
            } else {
                bulls++;
            }
        }
        return bulls + "A" + cows + "B";
    }
}

Last updated