程序员面试金典——17.5珠玑妙算
参考网址:https://www.nowcoder.com/profile/2708949/codeBookDetail?submissionId=13283364
Solution1:算法
从题目中可以获取隐含信息:
“猜中” 属于 “伪猜中”,但是反过来不成立。
所有需要先统计猜中,
然后再统计伪猜中个数= 可能的伪猜中个数 - 猜中个数
因此代码就比较容易写出来。
class Result {
public:
vector<int> calcResult(string A, string guess) {
// write code here
int n1 = 0, n2 = 0;//n1是猜中,n2是伪猜中
map<char, int> arr1, arr2;
vector<int> res;
for (int i = 0; i < 4; ++i) {
++arr1[A[i]];
++arr2[guess[i]];
if(A[i] == guess[i])
++n1;//统计猜中的次数
}
//int s = A[i].size() < B.size() ? A.size(),B.size();
for (auto it = arr2.begin(); it != arr2.end(); ++it) {
if (A.find(it->first) != string::npos && it->second > 0) {
if(it->second < arr1[it->first])
n2 += it->second;
else
n2 += arr1[it->first];
//++n2;
//--(it->second);
}
}
n2 = n2 - n1;
res.push_back(n1);
res.push_back(n2);
return res;
}
};