/* * 299. Bulls and Cows * 2016-7-2 by Mingyang * 代码很丑,可是这个题目过于简单,不详谈 * 特殊case 1122-》1222 * guess里面的第一个2出现的时候会让我在cow上加1 * 所以我先遍历的相等的这样就不会错了,不过代码可以修改的优化的地方很多,有时间慢慢写 */ public static String getHint(String secret, String guess) { int bull = 0; int cow = 0; HashSet<Character> set = new HashSet<Character>(); int[] array = new int[10]; for (int i = 0; i < secret.length(); i++) { char a = secret.charAt(i); array[a - '0']++; set.add(a); } for (int i = 0; i < guess.length(); i++) { char b = guess.charAt(i); if (guess.charAt(i) == secret.charAt(i)) { bull++; array[b - '0']--; continue; } } for (int i = 0; i < guess.length(); i++) { char b = guess.charAt(i); if (set.contains(b) && guess.charAt(i) != secret.charAt(i)) { if (array[b - '0'] > 0) { cow++; array[b - '0']--; } } } String res = bull + "A" + cow + "B"; return res; }