C ++程序执行基于有限状态自动机的搜索
这是一个C++程序,用于执行基于有限状态自动机的搜索。具有有限状态数的自动机称为有限自动机。在此,给文本一个text[0…t-1]并给出一个模式p[0...p-1]。我们必须在文本中找到模式,并将其所有出现的位置打印在相应的索引处。
演算法
Begin Function void transitiontable(): 1) put the entries in first row and filled it up. All entries in first row are always 0 except the entry for p[0] character. Always we need to go to state 1. for p[0]. 2) Initialize longestprefixsuffix as 0. 3) for i = 1 to P. (Here P is the length of the pattern) a) Copy the entries from the row at index equal to longestprefixsuffix. b)更新条目 for p[i] character to i+1. c) Update longestprefixsuffix = TF[lps][pat[i]] where TT is the 2D array. End
示例
#include<iostream> #include<cstring> #define NO_OF_CHARS 512 using namespace std; //建立一个TF表,该表代表给定模式的有限自动机 void transitiontable(char *p, int P, int TT[][NO_OF_CHARS]) { int i, longestprefixsuffix = 0, y; //将条目放在第一行 for (y =0; y < NO_OF_CHARS; y++) TT[0][y] = 0; TT[0][p[0]] = 1; //将条目放入其他行 for (i = 1; i<= P; i++) { // Copy values from row at index longestprefixsuffix for (y = 0; y < NO_OF_CHARS; y++) TT[i][y] = TT[longestprefixsuffix][y]; //更新条目 TT[i][p[i]] = i + 1; //更新lps以填充下一行 if (i < P) longestprefixsuffix = TT[longestprefixsuffix][p[i]]; // TT is the 2D array which is being constructed. } } //在文本中打印所有出现的图案 void patternsearch(char *p, char *t) { int P = strlen(p); int T = strlen(t); int TT[P+1][NO_OF_CHARS]; transitiontable(p, P, TT); //通过FA处理文本。 int i, j=0; for (i = 0; i < T; i++) { j = TT[j][t[i]]; if (j == P) { cout<<"\n pattern is found at index: "<< i-P+1; } } } int main() { char *text = "AABAA ABBAACCDD CCDDAABAA"; //take the text as input char *pattern = "AABAA"; //take the pattern as input patternsearch(pattern, text); getchar(); return 0; }
输出结果
pattern is found at index: 0 pattern is found at index: 20