题目描述
Finding all occurrences of a pattern in a text is a problem that arises frequently in text-editing programs. Typically,the text is a document being edited,and the pattern searched for is a particular word supplied by the user. We assume that the text is an array T[1…n] of length n and that the pattern is an array P[1…m] of length m<=n.We further assume that the elements of P and T are all alphabets(∑={a,b…,z}).The character arrays P and T are often called strings of characters. We say that pattern P occurs with shift s in the text T if 0<=s<=n and T[s+1…s+m] = P[1…m](that is if T[s+j]=P[j],for 1<=j<=m). If P occurs with shift s in T,then we call s a valid shift;otherwise,we calls a invalid shift. Your task is to calculate the number of vald shifts for the given text T and pattern P.
查找文本中出现的所有模式是文本编辑程序中经常出现的问题。通常,文本是正在编辑的文档,搜索的模式是用户提供的特定单词。我们假设文本是长度为n的数组T[1…n],模式是一个长度为m<=n的数组P[1…m]。我们进一步假设P和T的元素都是字母(∑={a,b…,z})。字符数组P和T通常被称为字符串。如果0<=s<=n并且T[s+1… .s + m] = P[1…m](即如果T[s+j]=P[j],对于1<=j<=m)。如果P发生时s在T上移位,那么我们称之为有效移位;否则,我们称之为无效移位。您的任务是计算给定文本T和模式P的有效值移位数。
输入描述
For each case, there are two strings T and P on a line,separated by a single space.You may assume both the length of T and P will not exceed 10^6.
对于每种情况,一行上有两个字符串T和P,用一个空格隔开。你可以假设T和P的长度都不超过10^6。
输出描述
You should output a number on a separate line,which indicates the number of valid shifts for the given text T and pattern P.
您应该在单独的一行上输出一个数字,它指示给定文本T和模式P的有效移位数。
输入样例:
abababab abab
输出样例:
3
思路
题目意思相当于找到字符串T有几个位置开始可以得到字符串P
- 可直接暴力循环得到答案
- 使用c++STL中的string方法
代码
#include<bits/stdc++.h>
#define MaxSize 1000000
using namespace std;
int main(){
char t[MaxSize],p[MaxSize];
while(scanf("%s %s",t,p)!=EOF){
int len1 = strlen(t);
int len2 = strlen(p);
int count = 0;
for(int i = 0; i < len1-len2+1; i++){
int flag=1;
for(int j = 0; j < len2; j++){
if(t[i+j]!=p[j]){
flag = 0;
break;
}
}
if(flag==1){
count++;
}
}
printf("%d",count);
}
return 0;
}
#include<bits/stdc++.h>
using namespace std;
int main(){
string t,p;
cin>>t>>p;
int len1 = t.length();
int len2 = p.length();
int count = 0;
int i=t.find(p);
while(i != string::npos){
count++;
i = t.find(p, i+1);
}
cout<<count;
return 0;
}
方法2的运行时间比1要长一倍多
tips
str.find(str2),即当str2是str的字串时,返回其在str中第一次出现的位置;如果str2不是str的字串,返回string::npos(表示不存在的位置)
str.find(str2,pos),从str的pos号位开始区配str2