2022.2.15
子串匹配
#include <stdio.h>
#include <stdbool.h>
#include <stdlib.h>
#include <malloc.h>
typedef struct Str
{
char *ch;
int length;
} Str;
//比较操作
int StrCompare(Str *s1, Str *s2)
{
int i = s1->length, j = s2->length;
for (int a = 0; a < i && a < j; a++)
{
if (s1->ch[a] != s2->ch[a])
{
return (s1->ch[a]) - (s2->ch[a]);
}
}
// for循环结束 则说明其中一个串已经完了且两个串前面全部相同 此时比串的长度就行
return (s1->length) - (s2->length);
}
//求长度
int length(Str *s)
{
if (s->ch[0] == '\0' || s->ch == NULL)
return 0;
int i = 0;
while (s->ch[i] != '\0')
{
i++;
}
return i;
}
//求子串操作 pos为起始位置 len为子串的总长度
bool Substring(Str *s, Str *r, int pos, int len)
{
if (pos < 0 || pos > r->length || len < 0 || pos + len > r->length)
return false;
s->ch = (char *)malloc(sizeof(char) * (len + 1));
int j = 0;
if (len == 0)
{
s->ch = '\0';
s->length = 0;
return true;
}
else
{
for (int i = pos; i < pos + len; i++, j++)
{
s->ch[j] = r->ch[i];
}
s->ch[j] = '\0';
s->length = len;
return true;
}
}
//暴力算法1 用已知函数+循环
int Index(Str *str, Str *s)
{
if (str->ch[0] == '\0' || s->ch[0] == '\0')
return 0;
Str *c = (Str *)malloc(sizeof(Str));
int i = 0, j = (str->length) - (s->length) + 1;
for (i; i < j; i++)
{
c->ch = (char *)malloc(sizeof(char) * (s->length + 1));
Substring(c, str, i, s->length);
if (!StrCompare(c, s))
{
return i + 1;
}
}
return 0;
}
//暴力算法2 回溯数组下标算法
int Index2(Str *str, Str *s)
{
if (s->ch[0] == '\0')
return 0;
int i = 0, j = 0; // i对应str j对应s
int a = length(str), b = length(s);
for (i, j; i < a && j < b;)
{
if (str->ch[i] == s->ch[j])
i++, j++;
else
{
i = i - j + 1;
j = 0;
}
}
if (j == b)
return i - j + 1;
else
return 0;
}
//最大相同前后缀数表整体右移,0位置赋0,全部-1得next数组
// next数组0位置赋值为-1
//递推求next数组
void GetNext(char *p, int next[])
{
int Length = 7;
next[0] = -1;
int k = -1;
int j = 0;
while (j < Length - 1) // next最后的下标是j+1 所以j最多到len-2
{
if (k == -1 || p[j] == p[k])
{
next[j + 1] = k + 1;
j++;
k++;
}
else
{
k = next[k];
}
}
}
// kmp算法
int KMP(char *s, char *p, int next[])
{
int i = 0, j = 0;
int a = 7, b = 2;
while (i < a && j < b)
{
if (s[i] == p[j] || j == -1)
{
i++, j++;
}
else
{
j = next[j];
}
}
if (j == b)
return i - j + 1;
else
return 0;
}
int main()
{
Str *s, *s1;
s = (Str *)malloc(sizeof(Str));
s1 = (Str *)malloc(sizeof(Str));
s->ch = "Hua Wei P30-------.-";
s1->ch = "--.-";
s->length = length(s);
s1->length = length(s1);
int b = Index2(s, s1);
printf("%d\n", b);
int a = Index(s, s1);
printf("%d\n", a);
printf("------------------------------\n");
char *p = "ABCDABD";
int arr[7] = {0};
GetNext(p, arr);
int c = KMP(p, "BD", arr);
printf("%d\n", c);
return 0;
}