ITPub博客

首页 > 应用开发 > IT综合 > 算法strstr实现

算法strstr实现

原创 IT综合 作者:dongyu2013 时间:2014-04-19 07:39:51 0 删除 编辑
  1. #include   
  2.   
  3. const char *my_strstr(const char *str, const char *sub_str)  
  4. {  
  5.     for(int i = 0; str[i] != '\0'; i++)  
  6.     {  
  7.         int tem = i; //tem保留主串中的起始判断下标位置   
  8.         int j = 0;  
  9.         while(str[i++] == sub_str[j++])  
  10.         {  
  11.             if(sub_str[j] == '\0')  
  12.             {  
  13.                 return &str[tem];  
  14.             }  
  15.         }  
  16.         i = tem;  
  17.     }  
  18.   
  19.     return NULL;  
  20. }  
  21.   
  22. int main()  
  23. {  
  24.     char *s = "1233345hello";  
  25.     char *sub = "345";  
  26.     printf("%s\n", my_strstr(s, sub));  
  27.     return 0;  
  28. }  




点击(此处)折叠或打开

  1. int strstr(char *string, char *substring) 
  2. {
  3.    if (string == NULL || substring == NULL)
  4.           return -1;
  5.  
  6.    int lenstr = strlen(string); 
  7.    int lensub = strlen(substring);

  8.    if (lenstr < lensub)
  9.         return -1;
  10.  
  11.    int len = lenstr - lensub;
  12.    for (int i = 0; i <= len; i++) //复杂度为 O(m*n)
  13.    { 
  14.      for (int j = 0; j < lensub; j++)
  15.      {
  16.         if (string[i+j] != substring[j])
  17.              break;
  18.      }
  19.         if (j == lensub)
  20.           return i + 1;
  21.    }
  22.     return -1;
  23.  }


来自 “ ITPUB博客 ” ,链接:https://blog.itpub.net/29012686/viewspace-1145082/ ,如需转载,请注明出处,否则将追究法律责任。

请登录后发表评论 登录
全部评论

注册时间:2013-12-25

  • 博文量
    263
  • 访问量
    238073