题目
分析
虽然是一个中等题,但是其实十分的简单.我们只需要先按照最小长度遍历一遍两个字符串的前缀,然后统计一下同位置并且数字相同的结果,然后把这些点标记一下,然后将secret中没有匹配的加入哈希表,遍历guess来统计一下不同位置数字相同的答案即可.
代码
C++
class Solution {
public:
string getHint(string secret, string guess) {
int a = 0, b = 0;
unordered_map m;
// 按最小长度遍历
for(int i=0 ; i 0)
{
b++;
// 当前数字-1
m[x]--;
}
}
}
// 字符串拼接答案
return to_string(a) + "A" + to_string(b) + "B";
}
};
Java
class Solution {
public String getHint(String secret, String guess) {
int bulls = 0;
int[] cntS = new int[10];
int[] cntG = new int[10];
for (int i = 0; i < secret.length(); ++i) {
if (secret.charAt(i) == guess.charAt(i)) {
++bulls;
} else {
++cntS[secret.charAt(i) - '0'];
++cntG[guess.charAt(i) - '0'];
}
}
int cows = 0;
for (int i = 0; i < 10; ++i) {
cows += Math.min(cntS[i], cntG[i]);
}
return Integer.toString(bulls) + "A" + Integer.toString(cows) + "B";
}
}
作者:LeetCode-Solution



