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

没做出来。。。
其实应该是扫两遍。第一次把match的找出来计数。同时把不 match 的记录在hashmap 中。
第二遍,把不匹配的都统计出来。

并不难,只是要分两步走。

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

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

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容