时间限制:3000 ms | 内存限制:65535 KB
难度:3
**
原题描述
**
描述
Given two strings A and B, whose alphabet consist only ‘0’ and ‘1’. Your task is only to tell how many times does A appear as a substring of B? For example, the text string B is ‘1001110110’ while the pattern string A is ‘11’, you should output 3, because the pattern A appeared at the posit
输入
The first line consist only one integer N, indicates N cases follows. In each case, there are two lines, the first line gives the string A, length (A) <= 10, and the second line gives the string B, length (B) <= 1000. And it is guaranteed that B is always longer than A.
输出
For each case, output a single line consist a single integer, tells how many times do B appears as a substring of A.
样例输入
- 3
- 11
- 1001110110
- 101
- 110010010010001
- 1010
- 110100010101011
样例输出
- 3
- 0
3
**
解题分析
**
从题目描述中可以看出这是一道解决字符串匹配问题,具体是求解字符串A在字符串B中出现的次数
解法一:直接暴力求解,挨个字符串进行比较,记录匹配的字符串个数
#include <iostream>
#include <string>
using namespace std;
int main ()
{
int n;
cin>>n;
while(n--){
string s,s1;
cin>>s1>>s;
int len1=s.length(),len2=s1.length();
int res=0;
for(int i=0;i<len1-len2;i++){
int j;
for(j=0;j<len2;j++){
if(s[i+j]!=s1[j]) break;
}
if(j>=len2) res++;
}
cout<<res<<endl;
}
return 0;
}
提交上去,WA,我也不清楚为什么,不过我猜想:
1、这是一个时间复杂度高的的算法,爆了时间
2、算法太过呆板,在大数据样例的冲击下,输出结果不对
3、程序逻辑有问题
(具体是什么原因呢,我也米有去深究)
解法二: 利用STL中的find()函数
#include <iostream>
#include <string>
using namespace std;
int main ()
{
int n;
cin>>n;
while(n--){
string s,s1;
cin>>s1>>s;
int pos,res=0;
pos=s.find(s1);
while(pos!=string::npos){
res++;
pos=s.find(s1,pos+1);
}
cout<<res<<endl;
}
return 0;
}
轻松AC,其实代码差不多,就在于核心的实现不同而已,
解法三: 利用启发式的搜索,KMP算法,具体的实现就交给读者了
KMP算法算法是一种改进的字符串匹配算法,KMP算法的关键是利用匹配失败后的信息,尽量减少模式串与主串的匹配次数以达到快速匹配的目的。具体实现就是实现一个next()函数,函数本身包含了模式串的局部匹配信息。时间复杂度O(m+n)。
**
find()
**
字符串查询函数find()的具体知识
string::npos
这是string类中的一个成员变量,一般应用在判断系统查询函数的返回值上,若等于该值,表明没有符合查询条件的结果值。
find函数
在一个字符串中查找指定的单个字符或字符组。如果找到,就返回首次匹配的开始位置;如果没有找到匹配的内容,则返回string::npos。一般有两个输入参数,一个是待查询的字符串,一个是查询的起始位置,默认起始位置为0.
rfind函数
对一个串从尾至头查找指定的单个字符或字符组,如果找到,就返回首次匹配的开始位置;如果没有查到匹配的内容,则返回string::npos。一般有两个输入参数,一个是待查询的字符串,一个是查询的起始位置,默认起始位置为串尾部
另外还是find_first_of、find_last_of、find_first_not_of、find_last_not_of等函数
更多内容请关注我个人博客网站MyBlog