A的个数比较简单,只需要挨个位置比较即可。B的个数,需要先用一个数组记录secret中各数字出现的个数(需排除A情况),再遍历一遍看guess中的数字是否在secret中出现过,若是,则B个数加一。
class Solution {
public:
string getHint(string secret, string guess) {
int a = 0, b = 0;
vector<int>mp(10, 0);
for(int i = 0; i < secret.size(); i++){
if(secret[i] != guess[i]) mp[secret[i] - '0']++;
}
for(int i = 0; i < secret.size(); i++){
if(secret[i] == guess[i]) a++;
else if(mp[guess[i] - '0'] > 0){
b++;
mp[guess[i] - '0']--;
}
}
return to_string(a) + "A" + to_string(b) + "B";
}
};
也可以只遍历一遍:
class Solution {
public:
string getHint(string secret, string guess) {
int a = 0, b = 0;
vector<int>mp1(10, 0);
vector<int>mp2(10, 0);
for(int i = 0; i < secret.size(); i++){
if(secret[i] != guess[i]){
mp1[secret[i] - '0']++;
mp2[guess[i] - '0']++;
}else{
a++;
}
}
for(int i = 0; i < 10; i++){
b += min(mp1[i], mp2[i]);
}
return to_string(a) + "A" + to_string(b) + "B";
}
};