模式匹配算法

源码:     

    //模式匹配算法:时间复杂度(M+N)
        public static Hashtable getMatch(Hashtable hsMatch, string condition)//hsMatch:待匹配的原项(key:唯一标示原项,value:待匹配的值);condition为待匹配的目标项;返回匹配的集合
        {
            char[] temp = condition.ToCharArray();
            int[] next = new int[condition.Length];
            getNextVal(temp, ref next);
            char[] value;
            Hashtable matchHS = new Hashtable();
            foreach (DictionaryEntry dict in hsMatch)
            {
                value = dict.Value.ToString().ToCharArray();
                int k = 0, i = 0;
                //时间复杂度(M+N):M:表示目标字符的长度;N:表示待匹配字符串的长度
                while (k < temp.Length && i < value.Length)
                {
                    if (value[i] == temp[k])
                    {
                        k++;
                        i++;
                    }
                    else
                    {
                        k = next[k];
                        if (k == -1)
                        {
                            k = 0;
                            i++;
                        }
                    }

                }
                //匹配成功时保存到返回的hashTable
                if (k == temp.Length)
                {
                    matchHS.Add(dict.Key, dict.Value);
                }

            }
            return matchHS;

        }     
       
        //获取字符串的模式值
        static void getNextVal(char[] temp, ref int[] next)
        {

            // 求模式串temp的next函数值并存入数组 next。
            int j = 0, k = -1;
            next[0] = -1;
            while (j < temp.Length - 1)
            {
                if (k == -1 || temp[j] == temp[k])
                {
                    ++j; ++k;
                    if (temp[j] != temp[k])
                        next[j] = k;
                    else
                        next[j] = next[k];
                }// if
                else
                    k = next[k];
            }
        }

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值