Brute Force算法
比较简单好理解
#include <iostream>
int match(char *s, char *t);
int main()
{
char str_s[7] = "aaaaab";
char str_t[5] = "aaab";
int result = match(str_s, str_t);
if(result >= 0)
std::cout << "match: " << result << std::endl;
else
std::cout << "not match!\n";
return 0;
}
int match(char *s, char *t)
{
// i为s的index,j为t的index,初始化为0
// 当s[i]=t[j]时,i++,j++,否则i回溯到i-j+1, j回溯为0
// 直到j为t.lenth()+1,match成功,返回i-j
int i = 0, j = 0;
while(t[j] != '\0' && s[i] != '\0')
{
if(s[i] == t[j])
{
i++;
j++;
}
else
{
i = i-j+1;
j = 0;
}
}
if(t[j] == '\0')
return i-j;
else
return -1;
}
KMP算法有点复杂,我也是看了两三遍才看懂在干嘛。。
最后写完发现求 next 数组的方法跟书上不太一样,但书上写的不知道怎么求的
#include <iostream>
#include <string.h>
int match(char *s, char *t);
void next_cal(char *t, int *n);
int main()
{
char str_s[10] = "aaabaaaab";
char str_t[6] = "aaaab";
int result = match(str_s, str_t);
if(result >= 0)
std::cout << "match: " << result << std::endl;
else
std::cout << "not match!\n";
return 0;
}
int match(char *s, char *t)
{
// 先求出字符串t的next数组
// i为s的index,j为t的index,均初始化为0,s[i] == s[j] 时i++,j++,否则 j=next[j],继续比较
// j为t.lenth()+1时匹配成功,返回i-j的值,否则返回-1
if(!strlen(s) || !strlen(t))
return -1;
int next[strlen(t)];
next_cal(t, next);
// for(int i = 0; i < strlen(t); i++)
// std::cout << next[i] << " ";
int i = 0, j = 0;
int len_t = strlen(t);
int len_s = strlen(s);
// while(j < strlen(t) && i < strlen(s)) //没明白为啥这种写法j=-1的时候会跳出循环。。谁知道可以告诉我一下。。
while(j < len_t && i < len_s)
{
if(j == -1 || s[i] == t[j])
{
i++;
j++;
}
else
j = next[j];
std::cout << i << " " << j << std::endl;
}
if(t[j] == '\0')
return i-j;
else
return -1;
}
void next_cal(char *t, int *n)
{
n[0] = -1;
n[1] = 0;
int j,c,d;
bool find;
if(strlen(t) > 2)
{
for(int i = 2; i < strlen(t); i++)
{
for(j = i-1; j > 0; j--)
{
find = false;
c = j-1;
d = i-1;
while(c >= 0)
{
if(t[c] == t[d])
{
c--;d--;
}
else
break;
}
if(c < 0)
{
find = true;
break;
}
}
if(find)
{
n[i] = j;
}
else
n[i] = 0;
}
}
}