豆瓣面试题strstr)

/*(豆瓣2013面试题strstr) 有一个在给定字符串中查找子串的函数strstr, 该函数从给定的字符串src中查找substr并返回一个整数, 指明substr第一次出现的位置(从0开始计数),如果找不到则返回-1。

说明: 1、代码中不允许使用系统已有的库函数,所有用到的库函数都需要自己实现 2、允许使用任何编程语言,函数原型自行给定。

参考的C语言函数原型为 int strstr(char* src , char* substr) */

/*算法: 只要将src中长度为substr的子串拿出来和substr比较是否相等即可, 则从前往后拿出子串,第一个相等的即可*/

//时间复杂度: O((len0-len1)*len1),网上看到大部分人做的时间复杂度为O(len0*len1);

//空间复杂度: O(1);

 1 int my_strlen(const char *str)
 2 {
 3     if('' == *str)
 4         return 0;
 5     else
 6         return 1+ my_strlen(str+1);
 7 }
 8 
 9 int my_strcmp(const char *str0, const char *str1, int len)
10 {
11     int count = 0;
12     while(*str0 && *str1 && *str0 == *str1 && count < len){
13         str0++, str1++;
14         count++;
15     }
16     if(count == len)
17         return 0;
18     else
19         return *str0 - *str1;    
20 }
21 
22 int my_strstr(char* src , char* substr)
23 {
24     if(NULL == src || NULL == substr)
25             return -1;
26     //分别求出src及substr的长度
27     int len0 = my_strlen(src);
28     int len1 = my_strlen(substr);
29     if(len0 < len1)//如果src长度不及substr肯定不存在
30         return -1;
31 
32     int i;
33     //长度为len1的字串个数为: len0-len1
34     for(i = 0; i < len0-len1; i++)
35     {
36         if(my_strcmp(src+i, substr, len1) == 0)//如相等则返回下标
37             return i;
38     }
39 
40     return -1;//所有子串找完都没有找到相等的
41 }
42 
43 
44 //测试函数
45 int main()
46 {
47     int ret = my_strstr("hellohellosdf", "ell");
48     printf("%d
", ret);
49 
50     return 0;
51 }
原文地址:https://www.cnblogs.com/xuyh/p/3487171.html