官方写法更简单
class Solution {
public String getHint(String secret, String guess) {
char[] guessChars = guess.toCharArray();
int cow = 0;
int bulls = 0;
List<List<Integer>> positionList = new ArrayList<>();
for (int i = 0; i < 10; i++) {
positionList.add(new ArrayList<Integer>());
}
for (int i = 0; i < secret.length(); i++) {
positionList.get(secret.charAt(i) - '0').add(i);
}
int[] flag = new int[secret.length()];
for (int i = 0; i < guessChars.length; i++) {
if (guessChars[i] == secret.charAt(i)) {
bulls++;
flag[i] = 1;
}
}
for (int i = 0; i < guessChars.length; i++) {
if (guessChars[i] != secret.charAt(i)) {
List<Integer> tmpList = positionList.get(guessChars[i] - '0');
for (int j = 0; j < tmpList.size(); j++) {
if (flag[tmpList.get(j)] == 0) {
flag[tmpList.get(j)] = 1;
cow++;
break;
}
}
}
}
return bulls + "A" + cow + "B";
}
}