博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
字符串匹配问题,返回第一个匹配的下标 ,运用了KMP算法
阅读量:4059 次
发布时间:2019-05-25

本文共 1392 字,大约阅读时间需要 4 分钟。

KMP的核心是next数组

next数组是依据待匹配字符串计算出来的,和待匹配字符串的长度一致。

计算过程如下:

int[] next = new int[ne.length];        next[0] = -1;         int j = 0, k = -1;        while(j < needle.length() - 1){//计算next数组            if(k == -1 || ne[k] == ne[j]){                next[++j] = ++k;            }else{                k = next[k];            }        }

计算出next数组后,当待匹配字符串哪个字符串出现失配,则向右移动(失配下标 - next[失配下标])个位置。

​​class Solution {    public int strStr(String haystack, String needle) {        if(needle.length() > haystack.length())            return -1;        if(needle.length() == 0)            return 0;        char[] hs = haystack.toCharArray();        char[] ne = needle.toCharArray();        int[] next = new int[ne.length];        next[0] = -1;         int j = 0, k = -1;        while(j < needle.length() - 1){//计算next数组            if(k == -1 || ne[k] == ne[j]){                next[++j] = ++k;            }else{                k = next[k];            }        }        int i = 0, head;        while(i <= (haystack.length() - needle.length())){             head = i;             int m = 0;             for(m = 0; m < needle.length(); m++){                 if(ne[m] != hs[i]){                     i = head+(m-next[m]);                     break;                 }                 i++;             }            if(m == needle.length()){                return head;            }        }        return -1;    }}​​

 

转载地址:http://dizji.baihongyu.com/

你可能感兴趣的文章
【CryptoZombies - 1 Solidity 教程】013 永久存储变量(storage)和 临时存储变量(memory)
查看>>
【opencv学习笔记】013之形态学操作应用(trackbar应用)
查看>>
【CryptoZombies - 1 Solidity 教程】014 函数可见性
查看>>
【CryptoZombies - 1 Solidity 教程】015 接口interface
查看>>
【opencv学习笔记】014之上采样与降采样
查看>>
【opencv学习笔记】015之基本阈值操作
查看>>
【CryptoZombies - 1 Solidity 教程】016 函数多返回值&奖励实战
查看>>
【CryptoZombies - 2 Solidity 进阶】001 智能合约的不可篡改性与Ownable
查看>>
【积跬步以至千里】App Crashed - WriteMiniDump
查看>>
我努力是因为, 我想通过自己,带给这个世界点什么!
查看>>
数据结构基础笔记、基础知识总结、周周练汇总,通过代码,更快速掌握数据结构和算法知识!
查看>>
赛前必看!!NOIP竞赛及CSP认证初赛赛前辅导详细视频教程!!!
查看>>
完美解决AttributeError: module ‘torchvision.models‘ has no attribute ‘detection‘
查看>>
VMWare报错:无法获得VMCI驱动程序的版本:句柄无效。
查看>>
重磅!AI与区块链技术知识分享交流会!特邀贾志刚老师、双一流211高校研究生!
查看>>
入门卷积神经网络必备,基础、理论、实战一网打尽!
查看>>
Java报错:No enclosing instance of type learnJ is accessible.
查看>>
java学习(2)类变量与实例变量
查看>>
java学习(3)类的四大特性1
查看>>
java学习(4)类的四大特性2之继承
查看>>