码迷,mamicode.com
首页 > 其他好文 > 详细

Jan 13 - Bulls and Cows; String; HashSet;

时间:2016-01-14 13:55:00      阅读:91      评论:0      收藏:0      [点我收藏+]

标签:

直接用hashmap做的:

代码:

public class Solution {
    public String getHint(String secret, String guess) {
        if(secret == null || guess == null) return null;
        Map<Character, Integer> secretMap = new HashMap<>();
        Map<Character, Integer> guessMap = new HashMap<>();
        List<Character> list = new ArrayList<>();
        int len = secret.length();
        int numA = 0;
        int numB = 0;
        for(int i = 0; i < len; i++){
            char c1 = secret.charAt(i);
            char c2 = guess.charAt(i);
            if(c1 == c2) numA++;
            else{
                if(secretMap.containsKey(c1)) secretMap.put(c1, secretMap.get(c1)+1);
                else{
                    secretMap.put(c1, 1);
                    list.add(c1);
                }
                if(guessMap.containsKey(c2)) guessMap.put(c2, guessMap.get(c2)+1);
                else guessMap.put(c2, 1);
            }
        }
        for(int i = 0; i < list.size(); i++){
            char c = list.get(i);
            if(secretMap.containsKey(c) && guessMap.containsKey(c)) numB += Math.min(secretMap.get(c), guessMap.get(c));
        }
        return numA+"A"+numB+"B";
    }
}

  

Jan 13 - Bulls and Cows; String; HashSet;

标签:

原文地址:http://www.cnblogs.com/5683yue/p/5129842.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!