开发者

an efficent version similar to strstr [closed]

It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, ove开发者_JAVA百科rly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened, visit the help center. Closed 11 years ago.

here is a general implementation

int stridx (char[] src, char[] str){
    int i,j,k;
    for(i=0;i < (src.len - str.len);i++){
      for(j=i,k=0; str[k] != '\0' && str[k] == src[i]; j++,k++);
      if( k> 0 && str[k]=='\0') return i;
    }
    return -1;
}

The worst case of the algorithm could be n^2, if we have aaaaaaaaaaaaaaaaaaaaaaaa (assuming both src and str are very long, and the length of them is very close).

Can I have a better algorithm?


You could use the Boyer-Moore algorithm, which is O(n). Here's sample C code.


It's not necessary to calculate the length of the strings :

char *strr(char *s1,char *s2)
  {
    int i,j;
    for(i=0;s1[i];i++)
        if(s1[i]==s2[0])
            for(j=0;s1[i+j]==s2[j];j++)
                if(!s2[j+1]) return &s1[i];
    return NULL;
  }


http://en.wikipedia.org/wiki/Knuth%E2%80%93Morris%E2%80%93Pratt_algorithm is another linear time algorithm. OTOH, the simple algorithms stay because in practise they are faster for most of the strings people actually search with.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜