299. Bulls and Cows

光记得一刷应该是扫了两遍,其实一遍就行了。

不要想着用guess去match secret,要互相MATCH。

一样的话就BULL++
不一样的话,看情况。如果guess的当前字母在secret出现过,那么cows++;如果secret的字母在guess出下锅,也cows++.

guess用++代表出现一次,SECRET用--代表出现一次。。

public class Solution {
    public String getHint(String secret, String guess) {
        int bull = 0;
        int cows = 0;
        
        Map<Integer, Integer> map = new HashMap<Integer, Integer>();
        int[] nums = new int[10];
        for (int i = 0; i < secret.length(); i++) {
            if (secret.charAt(i) == guess.charAt(i)) bull++;
            else {
                int a = secret.charAt(i) - '0';
                int b = guess.charAt(i) - '0';
                if (nums[a] < 0) cows++;
                if (nums[b] > 0) cows++;
                nums[a]++;
                nums[b]--;
            }
        }

        return bull + "A" + cows + "B";
    }
}
posted @ 2016-11-05 11:45  哇呀呀..生气啦~  阅读(116)  评论(0)    收藏  举报