浅析 Sunday 算法
背景
Sunday 算法是 Daniel M.Sunday 于 1990 年提出的字符串模式匹配。
其效率在匹配隨機的字符串時比其他匹配算法還要更快。Sunday 算法的實現可比 KMP,BM 的實現容易太多。
算法過程
假定主串為 "HERE IS A SIMPLE EXAMPLE",模式串為 "EXAMPLE"。
(1)
從頭部開始比較,發現不匹配。則 Sunday 算法要求如下:找到主串中位于模式串后面的第一個字符,即紅色箭頭所指的 “空格”,再在模式串中從后往前找“空格”,沒有找到,則直接把模式串移到“空格” 的后面。
(2)
(3)
找到匹配。
完整代碼
/**
*
* author : 劉毅(Limer)
* date?? : 2017-07-30
* mode?? : C++
*/
?
#include?<iostream>
#include?<string>
?
#define?MAX_CHAR?256
#define?MAX_LENGTH?1000
?
using?namespace?std;
?
void?GetNext(string?&?p,?int?&?m,?int?next[])
{
????for?(int?i?=?0;?i?<?MAX_CHAR;?i++)
????????next[i]?= -1;
????for?(int?i?=?0;?i?<?m;?i++)
????????next[p[i]]?=?i;
}
?
void?Sunday(string?&?s,?int?&?n,?string?&?p,?int?&?m)
{
????int?next[MAX_CHAR];
????GetNext(p,?m,?next);
?
????int?j;??// s 的下標
????int?k;??// p 的下標
????int?i?=?0;
????while?(i?<=?n?-?m)
????{
????????j?=?i;
????????k?=?0;
????????while?(j?<?n?&&?k?<?m?&&?s[j]?==?p[k])
????????????j++,?k++;
?
????????if?(k?==?m)
????????????cout?<<?"在"?<<?i?<<?" 處找到匹配\n";
?
????????if?(i?+?m?<?n)
????????????i?+=?(m?-?next[s[i?+?m]]);
????????else
????????????return;
????}
?
????// PS: 匹配失敗不作處理
}
?
int?main()
{
????string?s,?p;
????int?n,?m;
?
????while?(cin?>>?s?>>?p)
????{
????????n?=?s.size();
????????m?=?p.size();
????????Sunday(s,?n,?p,?m);
????????cout?<<?endl;
????}
?
????return?0;
}
數據測試如下圖:
來源:https://www.61mon.com/index.php/archives/213/
總結
以上是生活随笔為你收集整理的浅析 Sunday 算法的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: “一边熬夜一边求不要猝死”,90后养生朋
- 下一篇: 学习 Python 编程的 19 个资源