描述
给出两个字符串A和B,判断A、B有多少个字符位置与字符都相同,有多少个字符在B和A中都出现了,但是位置不同
解决
用map去存A中字符(位置与值不同),用vector存B中独有的字符,最后遍历vector中的字符即可
class Solution {
public:
string getHint(string secret, string guess) {
int length1 = secret.size();
int length2 = guess.size();
int cnt1 = 0, cnt2 = 0;
map<char, int> pos;
map<char, int> has1;
vector<char> has2;
cout << length1 << endl;
for (int i = 0; i < length1; ++i)
{
if (secret[i] == guess[i])
{
pos[i] = 1;
++cnt1;
}
else
{
++has1[secret[i]];
has2.push_back(guess[i]);
}
}
for (auto it : has2)
{
if (has1[it] >= 1)
{
++cnt2;
--has1[it];
}
}
return to_string(cnt1) + "A" + to_string(cnt2) + "B";
}
};