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";
}
}

浙公网安备 33010602011771号