• 软件测试技术
  • 软件测试博客
  • 软件测试视频
  • 开源软件测试技术
  • 软件测试论坛
  • 软件测试沙龙
  • 软件测试资料下载
  • 软件测试杂志
  • 软件测试人才招聘
    暂时没有公告

字号: 小 中 大 | 推荐给好友 上一篇 | 下一篇

c# kmp算法 (边界条件未处理好,有待改正)

发布: 2007-6-30 23:38 | 作者: admin | 来源: | 查看: 19次 | 进入软件测试论坛讨论

领测软件测试网  

using System;

namespace kmp
{
 /// <summary>
 /// Summary description for Class1.
 /// </summary>
 class Class1
 {
  /// <summary>
  /// The main entry point for the application.
  /// </summary>
  static int[] next=new int[20];
  static int count=0;
  static int kmp(char[] a, char[] b, int pos)
  {
   int i=pos, j=0;
   int lena=a.Length,lenb=b.Length;
   count=0;
   while((i<=lena-1)&&(j<=lenb-1))
   {
    if(a[i]==b[j])
    {++i;++j;}
    else
    {i=i-j+1; j=0;}
    count++;
   }
   if(j>lenb-1)
    return i-lenb;
   else
    return 0;
  }
  [STAThread]
  static void Main(string[] args)
  {
   //
   // TODO: Add code to start application here
   //
   int pos=0,reval;
   Console.WriteLine("input string1");
   string s1=Console.ReadLine();
   Console.WriteLine("input string2");
   string s2=Console.ReadLine();
   char[] p1=s1.ToCharArray();
   char[] p2=s2.ToCharArray();
   Console.WriteLine("lena={0},lenb={1}",p1.Length,p2.Length);
   reval=kmp(p1,p2,pos);
   Console.WriteLine("====not kmp ====");
   Console.WriteLine("value={0},count={1}",reval,count);
   get_next(p2,next);
   reval=index_kmp(p1,p2,pos);
   Console.WriteLine("====this is kmp ====");
   Console.WriteLine("value={0},count={1}",reval,count);
   get_goodnext(p2,next);
   reval=index_kmp(p1,p2,pos);
   Console.WriteLine("====this is good kmp ====");
   Console.WriteLine("value={0},count={1}",reval,count);
   Console.ReadLine();
  }
  static int index_kmp(char[] a,char[] b, int pos)
  {
   int i=pos, j=0;
   int lena=a.Length,lenb=b.Length;
   count=0;
   while((i<=lena-1)&&(j<=lenb-1))
   {
    if(j==0||a[i]==b[j])
    {++i;++j;}
    else
    {j=next[j];}
    count++;
   }
   if(j>lenb-1)
    return i-lenb;
   else
    return 0;
  }
  static void get_next(char[] a,int[] next)
  {
   int i=1,j=0;
   next[0]=0;
   while(i<=a.Length-2)
   {
    if(j==0||a[i]==a[j])
    {++i;++j;next[i]=j;}
    else
    {j=next[j];}
   }
  }
  static void get_goodnext(char[] a,int[] next)
  {
   int i=1,j=0;
   next[0]=0;
   while(i<=a.Length-2)
   {
    ++i;++j;
    if(j==0||a[i]==a[j])
    {
     if(a[i]!=a[j])
     {
      next[i]=j;
     }
     else
     {
      next[i]=next[j];
     }
    }
    else
    {j=next[j];}
   }
  }
 }
}


延伸阅读

文章来源于领测软件测试网 https://www.ltesting.net/


关于领测软件测试网 | 领测软件测试网合作伙伴 | 广告服务 | 投稿指南 | 联系我们 | 网站地图 | 友情链接
版权所有(C) 2003-2010 TestAge(领测软件测试网)|领测国际科技(北京)有限公司|软件测试工程师培训网 All Rights Reserved
北京市海淀区中关村南大街9号北京理工科技大厦1402室 京ICP备10010545号-5
技术支持和业务联系:[email protected] 电话:010-51297073

软件测试 | 领测国际 | ISTQB | ISTQB官网 | TMMi | TMMi认证 | 国际软件测试工程师认证 | 领测软件测试网