C语言KMP算法实现
使用到的头文件
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
strstr 实现
char *strstr(const char *srcStr, const char *subStr)
{
if (!srcStr || !subStr) return (char *)NULL;
const int subSize = strlen(subStr);
int *next = malloc(sizeof(int) * subSize);
if (next == NULL) return (char *)NULL;
int i = 0;
int j = -1;
next[i] = j;
while (i < subSize - 1)
{
if ((j == -1) || (subStr[i] == subStr[j]))
next[i] = (subStr[++i] == subStr[++j]) ? next[j] : j;
else
j = next[j];
}
i = j = 0;
const int srcSize = strlen(srcStr);
while (i < srcSize && j < subSize)
{
j = (j == -1 || srcStr[i] == subStr[j]) ? (i++, j + 1) : next[j];
}
if (next != NULL)
{
free(next);
next = NULL;
}
return (char *)((j == subSize) ? (srcStr + i - subSize) : NULL);
}
strrstr 实现
char *strrstr(const char *srcStr, const char *subStr)
{
if (!srcStr || !subStr) return (char *)NULL;
const int srcSize = strlen(srcStr);
const int subSize = strlen(subStr);
int i = subSize - 1;
int j = subSize;
int *prefix = malloc(sizeof(int) * subSize);
if (prefix == NULL) return (char *)NULL;
prefix[i] = j;
while (i > 0)
{
if ((j == subSize) || (subStr[i] == subStr[j]))
prefix[i] = (subStr[--i] == subStr[--j]) ? prefix[j] : j;
else
j = prefix[j];
}
i = srcSize - 1, j = subSize - 1;
while (i >= 0 && j >= 0)
{
j = (j == subSize || srcStr[i] == subStr[j]) ? (i--, j - 1) : prefix[j];
}
if (prefix != NULL)
{
free(prefix);
prefix = NULL;
}
return (char *)((j == -1) ? (srcStr + i + 1) : NULL);
}
|