zoukankan      html  css  js  c++  java
  • 字符串匹配—KMP算法

    KMP算法是一种改进的字符串匹配算法,由D.E.Knuth,J.H.Morris和V.R.Pratt提出的,因此人们称它为克努特—莫里斯—普拉特操作(简称KMP算法)。KMP算法的核心是利用匹配失败后的信息,尽量减少模式串与主串的匹配次数以达到快速匹配的目的。具体实现就是通过一个next()函数实现,函数本身包含了模式串的局部匹配信息。KMP算法的时间复杂度O(m+n) 。
    实现方式就不再这里献丑了,网上很多讲解,此处只是记录下c#实现的代码。

    public class KMP
    {
        public static int[] GetNext(String ps)
        {
            char[] p = ps.ToArray();
            int[] next = new int[p.Length];
            next[0] = -1;
            int j = 0;
            int k = -1;
            while (j < p.Length - 1)
            {
                if (k == -1 || p[j] == p[k])
                {
                    next[++j] = ++k;
                }
                else
                {
                    k = next[k];
                }
            }
            return next;
        }
    
        public static int GetIndex(String ts, String ps)
        {
            char[] t = ts.ToArray();
            char[] p = ps.ToArray();
            int i = 0; // 主串的位置
            int j = 0; // 模式串的位置
            int[] next = GetNext(ps);
            while (i < t.Length && j < p.Length)
            {
                if (j == -1 || t[i] == p[j])
                { 
                    // 当j为-1时,要移动的是i,当然j也要归0
                    i++;
                    j++;
                }
                else
                {
                    // i不需要回溯了
                    // i = i - j + 1;
                    j = next[j]; // j回到指定位置
                }
            }
    
            if (j == p.Length)
            {
                return i - j;
            }
            else
            {
                return -1;
            }
        }
    }
    
    //test
    static void Main(string[] args)
    {
        Console.WriteLine( KMP.GetIndex("abcdbcxdbc", "dbc"));
        Console.ReadKey();
    }

  • 相关阅读:
    POJ 3672 水题......
    POJ 3279 枚举?
    STL
    241. Different Ways to Add Parentheses
    282. Expression Add Operators
    169. Majority Element
    Weekly Contest 121
    927. Three Equal Parts
    910. Smallest Range II
    921. Minimum Add to Make Parentheses Valid
  • 原文地址:https://www.cnblogs.com/xtt321/p/14022697.html
Copyright © 2011-2022 走看看