您好,欢迎来到二三娱乐。
搜索
您的当前位置:首页Leetcode - Bulls and Cows

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";
    }
}

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

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

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

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

Copyright © 2019- yule263.com 版权所有 湘ICP备2023023988号-1

违法及侵权请联系:TEL:199 1889 7713 E-MAIL:2724546146@qq.com

本站由北京市万商天勤律师事务所王兴未律师提供法律服务