当前位置:学者斋 >

计算机 >C语言 >

c#实现sunday算法实例

c#实现sunday算法实例

Sunday算法思想跟BM算法很相似,在匹配失败时关注的是文本串中参加匹配的最末位字符的下一位字符,下面小编为大家整理了c#实现sunday算法实例,希望能帮到大家!

c#实现sunday算法实例

因正则表达式搜索总是出现死循环,开始考虑改为其他搜索方式,因为自带的IndexOf默认只能找到第一个或最后一个,如果要把全部的匹配项都找出来,还需要自己写循环SubString,所以想找下有没有现成的,就发现了在这个领域里,BM算法是王道,而sunday算法据说是目前最好的改进版,这一点我没有从国外的网站尤其是wiki上找到印证,但中文谈论sunday的文章很多,我就姑且认为它是最好的`吧。

复制代码 代码如下:

public static int SundaySearch(string text, string pattern)

{

int i = 0;

int j = 0;

int m = th ;

int matchPosition = i;

while (i < th && j < th)

{

if (text[i] == pattern[j])

{

i++;

j++;

}

else

{

if(m==th-1)break;

int k = th - 1;

while (k >= 0 && text[m ] != pattern[k])

{

k--;

}

int gap = th - k;

i += gap;

m = i + th;

if (m > th) m = th - 1;

matchPosition = i;

j = 0;

}

}

if (i <= th)

{

return matchPosition;

}

return -1;

}

好了,现在测试下性能:

复制代码 代码如下:

public static void PerformanceTest()

{

StreamReader reader = new StreamReader("D:", I);

string context = ToEnd();

string pattern = "xxxx";

int count = 1000*10;

Stopwatch watch=new Stopwatch();

//t();

//for (int i = 0; i < count; i++)

//{

// int pos= ositionFirst(context, pattern, true);

//}

//();

//eLine(sedMilliseconds);

t();

t();

for (int i = 0; i < count; i++)

{

int pos = xOf(pattern);

}

();

eLine(sedMilliseconds);

t();

t();

for (int i = 0; i < count; i++)

{

int pos = aySearch(context, pattern);

}

();

eLine(sedMilliseconds);

}

在可以找到匹配与不能找到匹配两种情况下,sunday算法耗时大概是indexof的20%左右。算法确实有用。

但千万不要使用substring来实现算法,那样会新生成很多字符串中间变量,算法带来的好处远远不如分配内存复制字符串的消耗大,注释掉的部分就是使用substring实现的,比indexof慢很多。

标签: sunday 实例 算法
  • 文章版权属于文章作者所有,转载请注明 https://xuezhezhai.com/jsj/cyuyan/go66vl.html