Leetcode - Bulls and Cows

My code:

public class Solution {
    public String getHint(String secret, String guess) {
        if (secret == null || guess == null) {
            return null;
        }
        
        HashMap<Character, Integer> map = new HashMap<Character, Integer>();
        int bull = 0;
        for (int i = 0; i < secret.length(); i++) {
            if (secret.charAt(i) == guess.charAt(i)) {
                bull++;
            }
            else {
                if (!map.containsKey(secret.charAt(i))) {
                    map.put(secret.charAt(i), 1);
                }
                else {
                    map.put(secret.charAt(i), map.get(secret.charAt(i)) + 1);
                }
            }
        }
        int cow = 0;
        for (int i = 0; i < secret.length(); i++) {
            if (secret.charAt(i) != guess.charAt(i) && map.containsKey(guess.charAt(i))) {
                if (map.get(guess.charAt(i)) > 0) {
                    cow++;
                    map.put(guess.charAt(i), map.get(guess.charAt(i)) - 1);
                }
            }
        }
        
        return bull + "A" + cow + "B";
    }
}

reference:
https://discuss.leetcode.com/topic/28445/c-4ms-straight-forward-solution-two-pass-o-n-time/9

沒做出來。。。
其實應(yīng)該是掃兩遍。第一次把match的找出來計數(shù)。同時把不 match 的記錄在hashmap 中。
第二遍,把不匹配的都統(tǒng)計出來。

并不難,只是要分兩步走。

Java HashMap get 操作,如果key不存在于 map中,就返回 null

Anyway, Good luck, Richardo! -- 09/22/2016

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容