南阳理工oj题目练习---Binary String Matching

来源:互联网 发布:中国环境监测实时数据 编辑:程序博客网 时间:2024/05/18 14:44

我的代码:

#include <iostream>#include <string>using namespace std;int main(){int N,pos,count;string A,B;cin>>N;while(N--){    cin>>A>>B;count=pos=0;while(pos=B.find(A.c_str(),pos),pos!=string::npos){count++;pos++;}cout<<count<<endl;}return 0;}

算法点评:

   总感觉有跟好的算法,这题好像是要凸显C++强大的位运算能力的,可我嫌麻烦就用了普通的子符串查找方法,可能是用的少的缘故吧。

  我开始想用位运算实现的思路是这样的:  把A对应的十进制数计算出来,这个应该不算麻烦。然后在B中取出所有和A的位数个字串转换为对应的十进制数存到一个数组中。

  最后遍历和做这样的运算: A&B+(~A)&(~B),又得同学可能一眼就看出来这就是传说中的同或运算,如果全1,就说明数组中的该元素和A是相同的。

好吧,我的表达能力不强,能看懂的就将就着看吧,。 总之一句,同或运算


oj推荐的最优算法:(感觉和我的一样,为毛线比我用的内存少呢?纳闷...)

#include<iostream>#include<string>using namespace std;int main(){string s1,s2;int n;cin>>n;while(n--){cin>>s1>>s2;unsignedint m=s2.find(s1,0);int num=0;while(m!=string::npos){num++;m=s2.find(s1,m+1);}cout<<num<<endl;}}




原创粉丝点击