数据结构和算法分析数据结构与算法

Leetcode-299 猜数字游戏

2021-11-10  本文已影响0人  itbird01

299. 猜数字游戏

解题思路

解法
1.分析题意,找出公牛和奶牛的个数
2.遍历secret,找出所有公牛,将secret剩余字符,用map存储,key为当前字符,value为出现的位置列表
3.遍历guess,跳过公牛,如果map中包含guess中字符,则为奶牛

解题遇到的问题

1.map降维

后续需要总结学习的知识点

是否有其他解法?

##解法1
iclass Solution {
    public String getHint(String secret, String guess) {
        // 分析题意,找出公牛和奶牛的个数
        int gNum = 0, nNum = 0;
        HashMap<Character, List<Integer>> map = new HashMap<>();
        for (int i = 0; i < secret.length(); i++) {
            if (secret.charAt(i) == guess.charAt(i)) {
                // 找出所有公牛
                gNum++;
            } else {
                // 将secret剩余字符,用map存储,key为当前字符,value为出现的位置列表
                List<Integer> index = new ArrayList<Integer>();
                index.add(i);
                if (map.containsKey(secret.charAt(i))) {
                    index.addAll(map.get(secret.charAt(i)));
                }
                map.put(secret.charAt(i), index);
            }
        }

        for (int i = 0; i < guess.length(); i++) {
            //跳过公牛
            if (guess.charAt(i) == secret.charAt(i)) {
                continue;
            }
            
            //如果map中包含guess中字符,则为奶牛
            if (map.containsKey(guess.charAt(i))) {
                List<Integer> index = map.get(guess.charAt(i));
                nNum++;
                index.remove(0);
                if (index.isEmpty()) {
                    map.remove(guess.charAt(i));
                } else {
                    map.put(guess.charAt(i), index);
                }
            }
        }
        return gNum + "A" + nNum + "B";
    }
}
上一篇 下一篇

猜你喜欢

热点阅读