• 串的模式匹配算法之二:首尾匹配算法


    using System;
    namespace EasyIndex
    {
        
    class Index
        
    {
            
    static void Main(string[] args)
            
    {
                
    string s="acabaabcaabaabcac";
                
    string m="abaabcac";
                
    int i=0;
                
    int j=0;
                
    while(i<s.Length && j<m.Length)
                
    {
                    
    if(s[i]==m[0])//判断两串的第一个元素是否相等
                    {
                        
    if(s[i+m.Length-1]==m[m.Length-1])//如果头元素相等,再判断尾元素是否相等;
                        {
                            i
    =1;
                            j
    =0;
                            
    while(i<s.Length && j<m.Length)//如果头尾都相等,再从第二个元素到倒数第二个元素判断;
                            {
                                
    if(s[i]==m[j])
                                
    {
                                    i
    ++;
                                    j
    ++;
                                }

                                
    else
                                
    {
                                    i
    =i-j+1;
                                    j
    =0;
                                }

                            }

                        }

                        
    else
                        
    {
                            i
    =i-j+1;
                            j
    =0;
                        }

                    }

                    
    else
                    
    {
                        i
    =i-j+1;
                        j
    =0;
                    }

                  }

                
    if(j>=m.Length)//说明m是s的一个子串,而且pos是i-m.Lengh+1,因为数组从0开始计数;
                {
                    Console.WriteLine(
    "m与s中第"+Convert.ToString(i-m.Length+1)+"个元素开始的子串相匹配!");
                }

                
    else
                
    {
                    Console.WriteLine(
    "m不是s的子串!");
                }


            }

        }

    }

  • 相关阅读:
    java利用zxing编码解码一维码与二维码
    Spring和MyBatis环境整合
    ML中Boosting和Bagging的比較
    理解x64代码模型
    python list.remove(),del()和filter &amp; lambda
    限制文本域中字符输入个数
    arcgis api for flex之专题图制作(饼状图,柱状图等)
    Linux I/O复用中select poll epoll模型的介绍及其优缺点的比較
    开发H5游戏引擎的选择:Egret或Laya?
    C++刷题——2830: 递归求1*1+2*2+3*3+……+n*n
  • 原文地址:https://www.cnblogs.com/gmq/p/515610.html
Copyright © 2020-2023  润新知