1. 程式人生 > >leetcode:(299) Bulls and Cows(java)

leetcode:(299) Bulls and Cows(java)

題目:

You are playing the following Bulls and Cows game 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.

Write a function to return a hint according to the secret number and friend's guess, use A to indicate the bulls and B to indicate the cows. 

Please note that both secret number and friend's guess may contain duplicate digits.

題目大意:

你正和你的朋友一起玩下面的公牛和母牛遊戲:你寫下一個數字然後讓你的朋友猜猜這個數字是多少。 每當你的朋友做出猜測時,你提供一個提示,表明所述猜測中有多少位數與你的密碼完全匹配,包括數字和位置(稱為“公牛”)以及有多少位數與祕密號碼相匹配但位於錯誤的位置 (稱為“奶牛”)。 您的朋友將使用連續的猜測和提示最終得出密碼。

根據祕密號和朋友的猜測寫一個函式來返回提示,用A表示公牛,用B表示奶牛。

請注意,密碼和朋友的猜測都可能包含重複的數字。

程式碼及解題思路如下:

package LeetCode_HashTable;

public class GetHint_299_1022 {
    public String GetHint(String secret, String guess) {
        int bulls = 0;//記錄公牛的個數
        int cows = 0;//記錄母牛的個數

        int length = secret.length();
        int[] nums = new int[10];//建立一個長度為10的陣列,用來存放0-9出現的次數

        for (int i = 0; i < length; i++) {
            int s = Character.getNumericValue(secret.charAt(i));
            int g = Character.getNumericValue(guess.charAt(i));

            if (s == g) { 
                bulls++;//如果在位置i處,s和g相等,那麼bulls++
            } else {
                if (nums[s] < 0) {
                    cows++; //如果在i處s和g不相等,並且s在已經出現過在g中的其他位置,cows++
                }
                if (nums[g] > 0) {
                    cows++; //如果在i處s和g不相等,並且g已經出現過在s中的其他位置,cows++
                }
                nums[s]++;
                nums[g]--;
            }
        }
        return bulls + "A" + cows + "B";
    }

    public static void main(String[] args) {
        String s = "1807";
        String g = "7810";

        GetHint_299_1022 test = new GetHint_299_1022();
        String result = test.GetHint(s, g);
        System.out.println(result);
    }
}