我想出了这个算法来匹配确切的字符串后,我试图了解已经在互联网上的和可怕的失败:P任何人都可以告诉我,如果这是快速还是慢与预先存在的算法相比?我的字符串匹配算法速度快吗?
#include <iostream>
#include<cstring>
using namespace std;
int main(){
int i=0;
int j=0;
int foo=0;
string str;
string needle;
cin>>str;
cin>>needle;
int * arr = NULL;
int * arr2 = NULL;
int * match = NULL;
arr = new int [str.length()];
int x=0, y = 0, z = 0;
int n=0; char a, b;
cout<<"\nStep 1: ";
for(i=0;i<str.length();i++){
if(str[i]==needle[0]){
arr[x]=i; x++;
cout<<i<<" ";
}
}
arr[x]=str.length(); x++; cout<<"\nStep 2: ";
if(x){
arr2 = new int [x];
for(i=0;i<x-1;i++){
if(arr[i+1]-arr[i]>=needle.length()){
arr2[y]=arr[i]; y++;
cout<<arr[i]<<" ";
}
}
delete[]arr; cout<<"\nStep 3: ";
if(y){
match = new int [y];
for(i=0;i<y;i++){
n=arr2[i];
for(j=0;j<needle.length(); j++){
a=str[n+j]; b=needle[j];
if(a==b){
foo=1;
}
else{
foo=0; break;
}
}
if(foo){
match[z]=n; z++;
cout<<n<<" ";
}
}
delete[]arr2;
if(z){
cout<<"\n\nMatches: ";
for(i=0;i<z;i++){
cout<<match[i]<<" ";
}
}
}
}
return 0;
}
使用'vector'而不是'new []',你会变得更好。如果你想知道它是否有效,你必须在对你很重要的情况下(即,在你自己的语料库上)实施替代方案和措施。 –