您的位置:首页 > 其它

Binary String Matching STL秒解-不要太简单

2017-03-02 19:47 274 查看
在解决这道题之前先介绍一下string类find()的调用。

string str; int found;

str.find("needles are small",found+1,6);从found+1的位置开始

在str中查找"needles are small"字符串的前6个字符 也就是"needle"

str.find(str2) 在str中查找str2字符串 若找不到则返回string::npos

rfind() 类似,只是从反向查找

#include <iostream>
#include <algorithm>
#include <vector>
#include <string>
using namespace std;
int main()
{

int n;cin>>n;
while(n--)
{

string s1,s2;
cin>>s1>>s2;
int found=0,count=0;
found=s2.find(s1);
while(found!=string::npos)
{
count++;
found=s2.find(s1,found+1);
}
cout<<count<<endl;
}
}


如要查找str2在str中出现多少次时 需要循环查找

        found=s2.find(s1);  第一句find一定要写在循环外面 不然很难去控制while的结束条件

        while(found!=string::npos)

        {

            count++;

            found=s2.find(s1,found+1); 在上次查找的基础上加一位继续查找

        }

一开始看以为是KMP的问题 后来发现string的STL就很容易解决问题直接上代码

其实很水到爆炸的题 我居然还在输入N后加了个getchar()导致CE了一次 也是无语。。。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: