-
Notifications
You must be signed in to change notification settings - Fork 30
/
Copy pathsunday.c
61 lines (53 loc) · 1.36 KB
/
sunday.c
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
/**
* @file sunday.c
* @author hutusi (hutusi@outlook.com)
* @brief Refer to sunday.h
* @date 2019-08-19
*
* @copyright Copyright (c) 2019, hutusi.com
*
*/
#include "sunday.h"
#include "def.h"
#include <string.h>
STATIC void
sunday_calculate_bad_chars(const char *pattern, int len, int *bad_chars)
{
for (int i = 0; i < 256; ++i) {
bad_chars[i] = -1;
}
for (int i = len - 1; i >= 0; --i) {
int ch = pattern[i];
if (bad_chars[ch] < 0) {
bad_chars[ch] = i;
}
}
}
int sunday_text_match(const char *text,
unsigned int text_len,
const char *pattern,
unsigned int pat_len)
{
int bad_chars[256];
sunday_calculate_bad_chars(pattern, pat_len, bad_chars);
int move = 0;
for (int i = 0; i < text_len; /* no ++i */) {
for (int j = 0; j < pat_len; /* no ++j */) {
if (text[i] == pattern[j]) {
++i;
++j;
} else {
move = pat_len - bad_chars[(int)text[pat_len + move]];
i = move;
j = 0;
}
}
/* here means j == pat_len */
return move;
}
return -1;
}
int sunday_string_match(const char *text, const char *pattern)
{
return sunday_text_match(text, strlen(text), pattern, strlen(pattern));
}