比较字符距离

/*输入2个串,都只含有a,b字符,步长为1移动,比较2个串中,不等的字符的累积个数*/

#include <iostream>
#include <string>
using namespace std;
/*
int ds( string s, string t)
{
int num = 0;
int ss = s.length();
int tt = t.length();
for (int i = 0; i < ss-tt+1; ++i)
{
int tm = 0;
while (tm<tt)
{
if (s[tm+i] != t[tm])
{
num++;
}
tm++;
}
cout<<"num="<<num<<endl;
}
return num;
}
int main()
{

string s , t;
cin >> s>> t;
//暴力法,全段比较
cout << ds(s, t) << endl;

return 0;
}
*/
int main()
{
//按串的思想去比较
for (string S, T; cin >> S >> T;){
int a = 0, b = 0;
int s = S.length(), t = T.length();
for (int j = 0; j < s - t + 1; ++j)
//a += S[i] == 'a', b += S[i] == 'b';
S[j] == 'a' ? ++a : ++b;
int ans = 0;
for (int i = 0; i < t; ++i){
ans += T[i] == 'a' ? b : a;
S[i] == 'a' ? --a : --b;
S[i + s - t + 1] == 'a' ? ++a : ++b;
}
cout << ans << endl;
}
return 0;
}

原文地址:https://www.cnblogs.com/beihaidao/p/8628576.html