299. Bulls and Cows

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.
For example:

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

Hint: 1 bull and 3 cows. (The bull is 8, the cows are 0, 1 and 7.)
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. 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.

Solution:hashmap count

Time Complexity: O(N) Space Complexity: O(10)

Solution Code:

class Solution {
    public String getHint(String secret, String guess) {
        
        int[] table = new int[10];
        int bull = 0, cow = 0;
        for(int i = 0; i < secret.length(); i++) {
            int a = secret.charAt(i) - '0';
            int b = guess.charAt(i) - '0';
            if(a == b) {
                bull++;
            }
            else {
                if(table[a] < 0) cow++;
                table[a]++;
                if(table[b] > 0) cow++;
                table[b]--;
            }
        }
        return "" + bull + "A" + cow + "B";
    }
}
最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容

  • 問題: You are playing the following Bulls and Cows game wit...
    Cloudox_閱讀 287評論 0 0
  • 問題 You are playing the following Bulls and Cows game with...
    RobotBerry閱讀 202評論 0 0
  • 昨晚睡覺前想看點書,隨手拿起床邊的一本雜志,閨女推薦的,《畢業了去遠方》。放在床邊好久了,只看過一兩頁。翻到一篇關...
    如果但凡是閱讀 322評論 0 0
  • 不多說直接上圖 這樣是可以將值傳遞到函數中的,但是下面的方式就不行 大家可以看下差別,具體因為什么我想大家再看了圖...
    Smallwolf_JS閱讀 437評論 0 0
  • 彩鉛真的的是耐心活 從構圖到上色 真的是一點一點完成的 用時3個小時畫了個蝴蝶結 總體還是不可以,明天在畫個
    一米之粒閱讀 284評論 1 1