思路
使用2个hash table,分别存储secret和guess中每个数字出现的次数。同时遍历两个数组,如果secret和guess对应的数字相同,那么A++;否则就将二者记录到对应的hash table中。最后同时遍历两个hash table,分别取每一个位置的secret和guess中的最小值作为匹配值,加到B上。
时间复杂度O(len)
空间复杂度O(len)
代码
class Solution {
public String getHint(String secret, String guess) {
if (secret == null || guess == null || secret.length() == 0) {
return null;
}
int[] secretHash = new int[10];
int[] guessHash = new int[10];
int A = 0, B = 0;
for (int i = 0; i < secret.length(); i++) {
char sc = secret.charAt(i);
char gc = guess.charAt(i);
if (sc == gc) {
A++;
} else {
secretHash[sc - '0']++;
guessHash[gc - '0']++;
}
}
for (int i = 0; i < 10; i++) {
B += Math.min(secretHash[i], guessHash[i]);
}
return A + "A" + B + "B";
}
}