Chinaunix首页 | 论坛 | 博客
  • 博客访问: 9987
  • 博文数量: 1
  • 博客积分: 15
  • 博客等级: 民兵
  • 技术积分: 20
  • 用 户 组: 普通用户
  • 注册时间: 2010-04-10 06:16
文章分类

全部博文(1)

文章存档

2015年(1)

我的朋友
最近访客

分类: LINUX

2015-09-18 15:19:55


正文


上篇文章(http://www.cnblogs.com/zzqcn/p/3508442.html)里提到的BF和KMP算法都是单模式串匹配算法,也就是说,模式串只有一个。当需要在字符串中搜索多个关键字(模式)时,则需要用到多模式串匹配算法。

简介

AC(Aho-Corasick)算法是一个经典的多模式串匹配算法,它借鉴了KMP算法的思想,可以由有限状态机(Finite State Automata:FSA)来表示。AC算法的基本原理是:

先根据多模式串建立一个有限状态自动机FSA,在进行模式匹配时,设当前状态为Scur,输入串中的当前符号为C,运行FSA,试图得到下一状态Snext。如果Snext无效,即发生失配,则根据规则,将当前状态回退到一个适合的状态Sfail,然后重复上一过程,直到Snext有效或Scur为0。在匹配的过程中,如果当前状态正好匹配了某个模式P,则输出它。


由AC算法的原理,我们可以知道,用于匹配的FSA与输入串无关,而只与模式串有关;匹配过程中如果发生失配,则FSA应回退到某一状态,而输入串指针无需回退。这两点都与KMP算法的思想吻合。

要实现基本的AC算法,即实现FSA逻辑,需要构建3样东西:

  1. 状态跳转表goto :决定对于当前状态S和条件C,如何得到下一状态S‘
  2. 失配跳转表fail : 决定goto表得到的下一状态无效时,应该回退到哪一个状态
  3. 匹配结果输出表output : 决定在哪个状态时输出哪个恰好匹配的模式


构造示例

原理比较抽象,下面以一个简单而且经典的例子(来自于AC算法创始人的论文)来演示一下AC算法的原理及goto、fail、output这3个表的构建。设多模式为 {“he”, “she”, “his”, “hers”}。下面来一步一步构建FSA。

首先规定一个初始状态0,接着依次处理多个模式串,首先是he:

 

每个圆圈代表一个状态(State),圆圈中的数字表示状态的编号;有向箭头代表状态的转换,它由当前状态指向下一状态,箭头上的字符表示此次状态转换的条件。

接下来是she,注意每处理一个模式串时,都要先回到起始状态0:

 

注意,如果给定条件C,从当前状态出发能转换到一个有效状态,那么只进行状态转换,而不创建新状态,这一点在处理后面两个模式串时可以看到。接着是his:

 

最后是hers,而且AC规定,当当前状态为初始状态(0)时,对于任意条件C来,都能转换到有效状态(这也避免了回退的死循环),因此,除了条件h和s外,对其他任意条件,状态0还应转换至状态0:

 


其实,最后的FSA图就表示了goto表,因为上面画的状态及状态转换都是有效的。另外,也可以自然地知道,每处理完一个模式时,FSA的当前状态都对应着此模式。因此,状态2,5,7,8分别对应模式he, she, his, hers,也就是2,5,7,8这4个状态对应的output表中的值。不过,到目前为止output表还未创建完成。

在下面的讨论中,我们用S’ = goto(S,C)表示状态S经由条件C转换到状态S‘,fail(S)表示状态S的fail表值,output(S)表示状态S的output表值。

goto表反映了有效的状态转换。而在fail表反映了转换失败时应回退到的状态。比如,设当前状态为2,当条件不是r时,状态转换就失败,必须回退到某一个合适的状态,这个状态就是状态2的fail值。而fail值的求法呢,和KMP算法中求next函数一样,可以用递推法来进行。

首先规定与状态0距离为1(即深度为1)的所有状态的fail值都为0。然后设当前状态是S1,求fail(S1)。我们知道,S1的前一状态必定是唯一的(从FSA图也可以看出),设S1的前一状态是S2,S2转换到S1的条件为C,测试S= goto(fail(S2), C),如果成功,则fail(S1) = goto(fail(S2), C),如果不成功,继续测试S= goto(fail(S3), C)是否成功,如此重复,直到转换到某个有效的状态Sn,令fail(S1) = Sn

做为例子,我们来求状态3,4,5的fail值。首先,按照约定fail(3) == 0。接着求fail(4),由于goto(fail(3), h) == goto(0, h) == 1,所以fail(4) == 1。接着求fail(5),由于goto(fail(4), e) == goto(1, e) == 2,所以fail(5) == 2。在这里我们注意到,当FSA的状态转换到状态5时,不仅匹配了she,而且匹配了he,这意味着对两个状态S和S’,S>S’,如果fail(S) == S‘,则output(S)应添加output(S’)。这样一来,output表也构建完整了。fail表如下:

状态 0 1 2 3 4 5 6 7 8 9
fail N/A 0 0 0 1 2 0 3 0 3


3个表构建完成后,就可以对输入串进行模式匹配了。设输入串为“ushers”,则匹配过程如下:

符号 状态转换 输出
u 0->0  
s 0->3  
h 3->4  
e 4->5 she he
r 5->2 2->8  
s 8->9 hers


 注意,虽然扫描到符号r时经历了状态2,但那只是一个中间状态,之后立刻切换到状态8,因此并不输出output(2)的内容{he},这也避免了模式”he”的重复输出。

至此,我们已经构建了goto,fail,output 3个必需的表。这时构建的FSA也叫做非确定性有限状态机(Nondeterministic Finite State Automata: NFA),也就是说,当匹配过程中发生失配时,应根据fail表进行状态回退,但具体回退到哪个状态为止,是不确定的,需要一次或多次循环回溯。可以预见,NFA会影响模式匹配的效率。可以通过构建确定性有限状态机(Deterministic Finite State Automata: DFA)来弥补这个缺陷,它的原理是,在当前状态下,对于任意条件,都可以确定地给出下一状态,而不需要进行循环。

设当前状态是S,条件为C,问题是如何求得下一个确定状态S‘。如果goto(S, C)成功,则S’ = goto(S, C);否则,令S‘ = goto(fail(S), C),如果S’有效且不为0,则S‘就是那个确定状态,此时,应把S’ = goto(S, C)这个关系添加到goto表中。可以预见,DFA会提高匹配速度,但由于向goto表添加了更多的条目,会导致存储消耗增加。

做为例子,我们来求状态1的确定状态{S’}。首先fail(1)==0。当C==e或i时,S‘不变,分别是2,6。当C==h时,由于goto(0,h)==1,所以S’==1。当C==s时,由于goto(0, s)==3,所以S’==3。对于其他条件C,goto(0, C)==0。因此,我们需要往之前构建的goto表添加两项:1=goto(1, h), 3=goto(1,s)。


C++简单实现

下面,用简单的C++代码来实现前文所述的AC算法,包括NFA和DFA形式。

简单介绍一下宏定义、数据结构和各函数的作用:

名称 类型 说明
AC_FAIL_STATE 无效/失败的跳转状态
AC_UNDEF_FAIL 未定义的fail表值
AC_CONT_SIZE 所有可能的条件,如果处理char字符,则范围是0-255
ac_transition 结构 goto表项,不含当前状态,因为它等于数组下标
FSAType 枚举 FSA类型,fail表创建后变为NFA,然后可以转换为DFA
ac_state_finder 函数对象 用于查找当前状态下符合输入条件的goto表项
ac_goto 函数 实现S'=goto(S, C)逻辑,用于goto表创建和模式匹配过程
ac_creat_goto_table 函数 创建goto表
ac_creat_fail_table 函数 创建fail表,完成后将实现NFA
ac_convert_to_DFA 函数 将NFA转换为DFA。会向goto表添加新项。完成后不再需要fail表
ac_print_goto_table 函数 打印所有状态及其对应的转换表、fail值(仅限NFA)、output值
ac_search 函数 AC搜索函数

还有,NFA和DFA的创建过程中,需要用到类似图的广度优先搜索(Breadth-First-Search:BFS)算法,因此用到了队列(std::queue)容器。


点击(此处)折叠或打开

  1. #include <vector>
  2. #include <queue>
  3. #include <algorithm>
  4. #include <functional>
  5. #include <string>
  6. #include <cstdio>
  7. using namespace std;




  8. #define AC_FAIL_STATE -1
  9. #define AC_UNDEF_FAIL -1
  10. #define AC_CONT_SIZE 256




  11. struct ac_transition
  12. {
  13.     char condition;
  14.     int next;
  15. };


  16. enum FSAType
  17. {
  18.     FSA_NULL = 0,
  19.     FSA_NFA,
  20.     FSA_DFA
  21. };




  22. struct ac_state_finder :
  23.         public binary_function<ac_transition, char, bool>
  24. {
  25.     bool operator() (const ac_transition& t, char c) const
  26.     {
  27.         return (t.condition == c);
  28.     }
  29. };




  30. vector<vector<ac_transition>> goto_table;
  31. vector<vector<string>> output_table;
  32. vector<int> fail_table;
  33. FSAType fsa_type = FSA_NULL;




  34. int ac_goto(int _state, char _cont);
  35. int ac_creat_goto_table(const vector<string>& _ptns);
  36. int ac_creat_fail_table();
  37. int ac_convert_to_DFA();
  38. int ac_print_goto_table();
  39. int ac_search(const string& _txt);




  40. int main(int argc, char** argv)
  41. {
  42.     string ss[4] = {"he", "she", "his", "hers"};
  43.     vector<string> ptns(ss, ss+4);
  44.     string txt = "ushers";


  45.     ac_creat_goto_table(ptns);
  46.     ac_creat_fail_table();
  47.     ac_print_goto_table();
  48.     ac_search(txt);


  49.     ac_convert_to_DFA();
  50.     ac_print_goto_table();
  51.     ac_search(txt);


  52.     return 0;
  53. }




  54. int ac_goto(int _state, char _cont)
  55. {
  56.     vector<ac_transition>::const_iterator ret =
  57.         find_if(goto_table[_state].begin(), goto_table[_state].end(),
  58.         bind2nd(ac_state_finder(), _cont));
  59.     if(goto_table[_state].end() == ret)
  60.     {
  61.         if(0 == _state)
  62.             return 0;
  63.         else
  64.             return AC_FAIL_STATE;
  65.     }
  66.     else
  67.         return ret->next;
  68. }




  69. int ac_creat_goto_table(const vector<string>& _ptns)
  70. {
  71.     int state = 0;
  72.     int state_id = 0;


  73.     ac_transition t;
  74.     vector<ac_transition> ts;
  75.     vector<string> ss;


  76.     goto_table.push_back(ts);
  77.     output_table.push_back(ss);
  78.     state_id++;


  79.     for(vector<string>::const_iterator i = _ptns.begin(); i != _ptns.end(); ++i)
  80.     {
  81.         state = 0;
  82.         for(string::const_iterator j=i->begin(); j<i->end(); ++j)
  83.         {
  84.             int next_state = ac_goto(state, *j);
  85.             if(0 == next_state || AC_FAIL_STATE == next_state)
  86.             {
  87.                 t.condition = *j;
  88.                 t.next = state_id++;
  89.                 goto_table[state].push_back(t);


  90.                 goto_table.push_back(ts);
  91.                 output_table.push_back(ss);


  92.                 state = t.next;
  93.             }
  94.             else
  95.                 state = next_state;
  96.         }
  97.         output_table[state].push_back(*i);
  98.     }
  99.   
  100.     return 0;
  101. }




  102. int ac_creat_fail_table()
  103. {
  104.     if(goto_table.empty())
  105.         return -1;


  106.     fail_table.resize(goto_table.size());
  107.     for(size_t i=0; i<goto_table.size(); ++i)
  108.         fail_table[i] = AC_UNDEF_FAIL;


  109.     queue<int> q;
  110.     for(vector<ac_transition>::const_iterator i = goto_table[0].begin();
  111.         i != goto_table[0].end(); ++i)
  112.     {
  113.         fail_table[i->next] = 0;
  114.         q.push(i->next);
  115.     }


  116.     int state;
  117.     while(!q.empty())
  118.     {
  119.         state = q.front(); q.pop();


  120.         for(vector<ac_transition>::const_iterator i = goto_table[state].begin();
  121.             i != goto_table[state].end(); ++i)
  122.         {
  123.             if(AC_UNDEF_FAIL != fail_table[i->next])
  124.                 continue;


  125.             q.push(i->next);


  126.             int prev_state = state, ret;
  127.             do
  128.             {
  129.                 prev_state = fail_table[prev_state];
  130.                 ret = ac_goto(prev_state, i->condition);
  131.             } while (AC_FAIL_STATE == ret);


  132.             fail_table[i->next] = ret;
  133.             
  134.             for(vector<string>::const_iterator j = output_table[ret].begin();
  135.                 j != output_table[ret].end(); ++j)
  136.             {
  137.                 vector<string>::const_iterator sret =
  138.                     find(output_table[i->next].begin(), output_table[i->next].end(), *j);
  139.                 if(output_table[i->next].end() == sret)
  140.                     output_table[i->next].push_back(*j);
  141.             }
  142.         }
  143.     }


  144.     fsa_type = FSA_NFA;


  145.     return 0;
  146. }




  147. int ac_convert_to_DFA()
  148. {
  149.     if(fsa_type != FSA_NFA)
  150.         return -1;


  151.     if(goto_table.empty() || fail_table.empty())
  152.         return -1;


  153.     queue<int> q;
  154.     for(vector<ac_transition>::const_iterator i = goto_table[0].begin();
  155.         i != goto_table[0].end(); ++i)
  156.     { q.push(i->next); }


  157.     int state;
  158.     while(!q.empty())
  159.     {
  160.         state = q.front(); q.pop();


  161.         for(size_t c=0; c<AC_CONT_SIZE; ++c)
  162.         {
  163.             int next_state = ac_goto(state, c);
  164.             if(next_state != AC_FAIL_STATE && next_state != 0)
  165.                 q.push(next_state);
  166.             else
  167.             {
  168.                 next_state = ac_goto(fail_table[state], c);
  169.                 if(next_state != AC_FAIL_STATE && next_state != 0)
  170.                 {
  171.                     ac_transition t;
  172.                     t.condition = c;
  173.                     t.next = next_state;
  174.                     goto_table[state].push_back(t);
  175.                 }
  176.             }
  177.         }
  178.     }


  179.     fail_table.clear();
  180.     fsa_type = FSA_DFA;


  181.     return 0;
  182. }




  183. void OutputMatch(int _state, size_t _pos)
  184. {
  185.     for(vector<string>::const_iterator i = output_table[_state].begin();
  186.         i != output_table[_state].end(); ++i)
  187.     {
  188.         printf("%d %s : %d\n", _state, i->c_str(), _pos - i->length());
  189.     }
  190. }


  191. int ac_search(const string& _txt)
  192. {
  193.     if(goto_table.empty() || FSA_NULL == fsa_type)
  194.         return -1;


  195.     int state = 0;
  196.     string::size_type i;
  197.     for(i=0; i<_txt.length(); ++i)
  198.     {
  199.         char c = _txt[i];
  200.         if(output_table[state].size() > 0)
  201.             OutputMatch(state, i);


  202.         if(FSA_NFA == fsa_type)
  203.         {
  204.             while(AC_FAIL_STATE == ac_goto(state, c))
  205.                 state = fail_table[state];
  206.             state = ac_goto(state, c);
  207.         }
  208.         else if(FSA_DFA == fsa_type)
  209.         {
  210.             state = ac_goto(state, c);
  211.             if(AC_FAIL_STATE == state)
  212.                 state = 0;
  213.         }
  214.     }


  215.     if(output_table[state].size() > 0)
  216.         OutputMatch(state, i);


  217.     return 0;
  218. }




  219. int ac_print_goto_table()
  220. {
  221.     if(goto_table.empty())
  222.         return -1;


  223.     int state_id = 0;
  224.     for(vector<vector<ac_transition>>::const_iterator i = goto_table.begin();
  225.         i != goto_table.end(); ++i, ++state_id)
  226.     {
  227.         printf("%d: ", state_id);


  228.         if(FSA_NFA == fsa_type)
  229.             printf("%d ", fail_table[state_id]);


  230.         for(vector<ac_transition>::const_iterator j = i->begin();
  231.             j != i->end(); ++j)
  232.         {
  233.             printf("%c->%d ", j->condition, j->next);
  234.         }


  235.         for(vector<string>::const_iterator j = output_table[state_id].begin();
  236.             j != output_table[state_id].end(); ++j)
  237.         {
  238.             printf("(%s) ", j->c_str());
  239.         }
  240.         printf("\n");
  241.     }
  242.     printf("\n");


  243.     return 0;
  244. }
输出结果:

0: -1 h->1 s->3
1: 0 e->2 i->6
2: 0 r->8 (he)
3: 0 h->4
4: 1 e->5
5: 2 (she) (he)
6: 0 s->7
7: 3 (his)
8: 0 s->9
9: 3 (hers)
she : 1
he : 2
hers : 2




0: h->1 s->3
1: e->2 i->6 h->1 s->3
2: r->8 h->1 s->3 (he)
3: h->4 s->3
4: e->5 h->1 i->6 s->3
5: h->1 r->8 s->3 (she) (he)
6: s->7 h->1
7: h->4 s->3 (his)
8: s->9 h->1
9: h->4 s->3 (hers)
she : 1
he : 2
hers : 2

阅读(1338) | 评论(0) | 转发(0) |
0

上一篇:没有了

下一篇:没有了

给主人留下些什么吧!~~