leetcode(76).299. Bulls and Cows

来源:互联网 发布:数据共享交换平台 ppt 编辑:程序博客网 时间:2024/06/10 10:56

题意:猜数字,给出xAyB,x是位置对了的数目,y是数字对了位置没对的数目。(重复的数字只能匹配一次)

初步分析:用hasmap记录每个数字出现了几次,然后遍历匹配位置,用hashmap的查找来匹配数目(没匹配成功一次,hashmap中对应数目减1),等于0就不匹配了(意味着匹配完了)

public class Solution {   public String getHint(String secret, String guess) {    int bulls = 0;    int cows = 0;    HashMap<Character, Integer> hm = new HashMap<Character, Integer>();    for (int i = 0; i < secret.length(); i++) {  //得到select各个数字出现了几次    if (hm.containsKey(secret.charAt(i))) {    hm.put(secret.charAt(i), hm.get(secret.charAt(i))+1);    } else {    hm.put(secret.charAt(i), 1);    }    }        for (int i = 0; i < guess.length(); i++) {    if (secret.charAt(i) == guess.charAt(i)) {   //位置相同    bulls++;    }        if (hm.containsKey(guess.charAt(i)) && hm.get(guess.charAt(i)) > 0) {  //serect没有或者已经匹配完了,就不算数字相同了    cows++;                                  //数字相同(secret中有这个数字)    hm.put(guess.charAt(i), hm.get(guess.charAt(i))-1);  //每匹配一次,secret中对应数目就少1,    }    }        cows -= bulls; //cows代表数字相同,但位置不同。        return new String(bulls+"A"+cows+"B");        }}


0 0
原创粉丝点击