(原题不说了,这里给出扩展的问题)
给定两个长度相等的字符串A和B,输出两个值n和m。如果A[i] == B[i],则n加1;如果A[i] == B[j] (i != j),则m加1。
思路:
思路比较直观。用一个大小为256的bool数组表示A中字符的出现。
#include <iostream>
#include <string>
#include <vector>
using namespace std;
void Compare(const string& s1, const string& s2, int& n, int& m)
{
if (s1.size() == 0 || s2.size() == 0 || s1.size() != s2.size())
{
n = m = -1;
return;
}
n = m = 0;
vector<bool> flag(256);
for (int i = 0; i < s1.size(); ++i)
flag[s1[i]] = true;
for (int i = 0; i < s1.size(); ++i)
{
if (s1[i] == s2[i])
++n;
else
{
if (flag[s2[i]])
++m;
}
}
}
int main()
{
string a("abcdefagh");
string b("asdfweasd");
int n, m;
Compare(a, b, n, m);
cout << n << " " << m << endl;
return 0;
}