Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/string/5.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
String 我的字符串匹配算法快吗?_String_C++11 - Fatal编程技术网

String 我的字符串匹配算法快吗?

String 我的字符串匹配算法快吗?,string,c++11,String,C++11,在我试图理解互联网上已经存在的字符串后,我提出了这个匹配精确字符串的算法,但失败了: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; i

在我试图理解互联网上已经存在的字符串后,我提出了这个匹配精确字符串的算法,但失败了: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;
}
#包括
#包括
使用名称空间std;
int main(){
int i=0;
int j=0;
int-foo=0;
字符串str;
线针;
cin>>str;
cin>>针;
int*arr=NULL;
int*arr2=NULL;
int*match=NULL;
arr=newint[str.length()];
int x=0,y=0,z=0;
int n=0;字符a,b;

不能像这样使用它:

arr = new int [str.length()]
它会给你一个编译时错误,但是你可以在Java中使用它

“谁能告诉我这是否足够有效…”

不,因为您没有描述使用该方法的上下文。在某些情况下,它肯定足够有效。在其他情况下,可能不会

这不是一个开玩笑的回答。有一个真正的要点:

效率本身很少是一个目标,在大多数情况下,特定代码段的效率在现实编程中没有什么实际意义

通常最好编写简单、正确的代码,并且在测量性能和分析应用程序以确定热点时只考虑微观级别的效率



现在,如果您对字符串搜索算法本身的性能感兴趣,那么我建议您从总结(并链接到)一些高级字符串搜索算法开始。

它在g++上运行得非常好:)至少对于小字符串(我尝试了最多26个字符和3个字符)对于字符串比较,第1步:检查两个字符串的大小,如果它们相等,则继续执行第2步,该步骤使用For循环进行比较。如果两个字符串的长度不相等,则可以推断字符串不相等。第一个输入
abcabdsbabababacadadefabc
第二个输入
abc
=正确的结果str为?:p匹配算法:这不是重点!真正的问题是“足够有效”。使用
向量
而不是
新[]
,你会更好。如果你想知道它是否有效,你必须在对你重要的情况下(即,在你自己的语料库上)实施替代方案和衡量。