Implementation:Sunday 字符串匹配

int sunday(string str, string pattern) {
int str_len = str.length();
int pat_len = pattern.length(); int char_pos[];
for (int i = ; i<; i++) char_pos[i] = -; for (int i = pat_len - ; i>=; i--) char_pos[pattern[i]] = i; int i = ;
int j = ; while (i + pat_len <= str_len) {
while (j < pat_len && str[i] == pattern[j]) {
i++, j++;
}
if (j == pat_len) return i - pat_len; int k = i + pat_len - j;
int p = ; while ( k < str_len && (p = char_pos[str[k]]) == -) {
k += pat_len;
} i = k - p;
j = ;
}
return -;
}

比KMP好理解多了

参考:

http://www.cnblogs.com/lbsong/archive/2012/05/25/2518188.html

简化:

 int sunday(const char* pattern, const char* str) {
if (pattern == NULL || str == NULL) {
return -;
}
int slen = , plen = ; while (pattern[plen] != '\0') plen++;
while (str[slen] != '\0') slen++; int tbl[];
for (int i=; i<; i++) tbl[i] = -;
for (int i=; i<plen; i++) tbl[pattern[i]] = i; int pi = , si = ; while (si < slen) {
while (str[si] == pattern[pi] && si < slen) si++, pi++;
if (pi == plen) return si - plen;
int nidx = plen - pi + si;
int offset = tbl[str[nidx]];
si = nidx - offset;
pi = ;
}
return -;
}
上一篇:系统学习NIO


下一篇:【BIRT】02_开发一张简单的报表