-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathKMPSearch.m
More file actions
64 lines (57 loc) · 1.35 KB
/
Copy pathKMPSearch.m
File metadata and controls
64 lines (57 loc) · 1.35 KB
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
58
59
60
61
62
63
64
//
// KMPSearch.m
// BaseAlgorithm
//
// Created by CC on 2020/4/29.
// Copyright © 2020 kayak. All rights reserved.
//
#import "KMPSearch.h"
@implementation KMPSearch
-(void)test{
char *stringTOSearch = "axssbdecabdecacabfd";
char *subStr = "decabdec";
int* next = getNext(subStr);
NSInteger len = strlen(subStr);
for (int i=0; i<len; i++) {
printf("%d ",next[i]);
}
int index = search(stringTOSearch, subStr);
printf("x -- %d",index);
}
int search(char *mainStr,char *subStr){
NSInteger lenMain = strlen(mainStr);
NSInteger lenSub = strlen(subStr);
int* next = getNext(subStr);
int index = -1;
for (int i=0,k=0; i<lenMain;) {
if(mainStr[i]==subStr[k]){
k++;
if(k>=lenSub){
index = i+1 - (int)lenSub;
}
i++;
}else {//失配
if(k>0)
k = next[k-1];
else {
i++;
}
}
}
return index;
}
int * getNext(char *str){
NSInteger len = strlen(str);
int *next = (int *)calloc(len, sizeof(int));
for (int i=1,k=0; i<len; i++) {
while (k>0&&str[k]!=str[i]) {
k = next[k-1];
}
if(str[k]==str[i]){
k++;
}
next[i] = k;
}
return next;
}
@end