-
Notifications
You must be signed in to change notification settings - Fork 4
/
Implement strStr().txt
57 lines (54 loc) · 1.3 KB
/
Implement strStr().txt
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
problem:
Implement strStr().
Returns a pointer to the first occurrence of needle in haystack, or null if needle is not part of haystack.
-----------------------------------------------------------------------
solution:
//考察字符串数组与指针的使用,直接暴力搜索,过小集合,大集合超时
char *strStr(char *haystack, char *needle)
{
if(needle == NULL || *needle == '\0')
return haystack;
char *p = haystack;
while(*p != '\0')
{
char *pBegin = p;
char *q = needle;
while(*q != '\0'&&*p != '\0' && *p == *q)
{
p++;
q++;
}
if(*q == '\0')
return pBegin;
p = pBegin + 1;
}
return NULL;
}
///////improved
//上面的暴力搜索外层循环了n次,n为haystack的长度,实际上只需要循环n-m+1次,因为长度不够m的时候肯定不可能匹配
//设个指针tail,开始时tail与开始间隔m,当tail指到字符串结束出,循环停止
char *strStr(char *haystack, char *needle)
{
if(needle == NULL || *needle == '\0')
return haystack;
char *p = haystack;
char *q = needle;
char *tail = haystack;
while(*++q != '\0')
tail++;
while(*tail != '\0')
{
char *pBegin = p;
q = needle;
while(*q != '\0'&&*p != '\0' && *p == *q)
{
p++;
q++;
}
if(*q == '\0')
return pBegin;
p = pBegin + 1;
tail++;
}
return NULL;
}