基本的模式搜索算法

Input:  txt[] = "THIS IS A TEST TEXT"
pat[] = "TEST"
Output: Pattern found at index 10

pat[] =  "AABA"
Output: Pattern found at index 0
Pattern found at index 9
Pattern found at index 12


// C program for Naive Pattern Searching algorithm
#include<stdio.h>
#include<string.h>
void search(char *pat, char *txt)
{
int M = strlen(pat);
int N = strlen(txt);
int i;
/* A loop to slide pat[] one by one */
for (i = 0; i <= N - M; i++)
{
int j;

/* For current index i, check for pattern match */
for (j = 0; j < M; j++)
if (txt[i+j] != pat[j])
break;

if (j == M)  // if pat[0...M-1] = txt[i, i+1, ...i+M-1]
printf("Pattern found at index %d \n", i);
}
}
/* Driver program to test above function */
int main()
{
char pat[] = "AABA";
search(pat, txt);
return 0;
}


输出：

Pattern found at index 0
Pattern found at index 9
Pattern found at index 13

1、什么是最好的情况？

txt[]  = "AABCCAADDEE"
pat[] = "FAA"

2、什么是最坏的情况？

1）当文本和图案的所有字符相同时。

txt[] = "AAAAAAAAAAAAAAAAAA"
pat[] = "AAAAA".

2）只有最后一个字符不同时也会发生最坏的情况。

txt[] = "AAAAAAAAAAAAAAAAAB"
pat[] = "AAAAB"

posted @ 2017-11-08 10:28 wongyi 阅读(...) 评论(...) 编辑 收藏