关于串的kmp匹配问题

最近在看数据结构串的部分是,对串的匹配十分感兴趣,在严蔚敏老师的数据结构书上也讲到了对串的相关操作,而其中对串的匹配让人十分感兴趣。接下来就看看串的匹配算法。

1.朴素模式匹配算法 这里就不过多解释了

2.KMP模式算法匹配

具体的java代码如下

package nec.cn.stringComp;


public class KMPMatch
{


    public static void main(String[] args)
    {
        String mainStr = "abcabcabdcabcabd";// 匹配串
        String patternStr = "abcabd";// 模式串
        int pLen = patternStr.length();
        int next[] = new int[pLen];
        caculate_next(next, patternStr);
        for (int i = 0; i < pLen; i++)
        {
            System.out.println("计算得到next数组:");
            System.out.print(next[i] + " ");
        }
        int find = match_KMP(mainStr, patternStr, next);
        System.out.println("match position is " + find);
    }


    public static void caculate_next(int[] next, String p)
    {
        // 此处设定next数组的第0位和第1位的值为-1和0
        next[0] = -1;
        next[1] = 0;
        int len = next.length;
        for (int i = 2; i < len; i++)
        {
            if (p.charAt(i - 1) == p.charAt(next[i - 1]))
            {
                next[i] = next[i - 1] + 1;
            } else
            {
                next[i] = 0;
            }
        }


    }


    public static int match_KMP(String m, String p, int[] next)
    {
        int mLen = m.length();
        int pLen = p.length();
        for (int i = 0, j = 0; i < mLen && j < pLen;)
        {
            if (m.charAt(i) == p.charAt(j))
            {
                // 如果i和j处的字符相等,则都加1
                if (j == pLen - 1)
                    return i - j;
                j++;
                i++;
            } else
            {
                // 不等的时候分两种情况讨论
                if (-1 == next[j])
                {
                    i++;
                    j = 0;
                } else
                    j = next[j];
            }
        }
        return -1;
    }


}


对于其中的next[j]数组,详情可以查看严蔚敏老师的书。



  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值