当前位置: 首页 > news >正文

leetcode 28 Find the Index of the First Occurrence in a String

 直接用kmp算法

class Solution {
public:
    int strStr(string haystack, string needle) {
        return kmp(haystack,needle);
    }

    int kmp(std::string &text,std::string &pattern){
        int n = text.size();
        int m = pattern.size();
        if(m == 0)
            return 0;
        std::vector<int> next;
        next.reserve(m);
        getNext(pattern,m,next);
        int j = -1;
        for(int i = 0;i < n;i++){
            while(j != -1 && text[i] != pattern[j+1]){
                j = next[j];
            }
            if(text[i] == pattern[j+1]){
                j++;
            }
            if(j == m-1)
                return i - j;
        }
        return -1;
    }

    void getNext(std::string &pattern,int len,std::vector<int> &next){
        next[0] = -1;
        int j = -1;
        for(int i = 1;i < len;i++){
            while(j != -1 && pattern[i] != pattern[j+1]){
                j = next[j];
            }
            if(pattern[i] == pattern[j+1])
                j++;
            next[i] = j;
        }
    }
};

或者另外一种写法,用的是部分匹配值(Partial Match)表

class Solution {
public:
    int strStr(string haystack, string needle) {
        return KMP(haystack,needle);
    }
    void getPM(std::string &pattern,int len,std::vector<int> &pm){
        pm[0] = 0;
        int j = 0;// j表示前缀的末尾元素的索引位置,同时它也是最长公共前后缀的长度
        //i表示后缀的末尾元素的索引位置
        for(int i = 1;i < len;i++){
            while(j > 0 && pattern[i] != pattern[j])
                j = pm[j-1];
            if(pattern[j] == pattern[i]) j++;
            pm[i] = j;
        }
    }
    int KMP(std::string &text,std::string& pattern){
        int m = pattern.size();
        if(m == 0) return 0;
        std::vector<int> pm;
        pm.resize(m);
        getPM(pattern,m,pm);
        int n = text.size();
        int j = 0;
        for(int i = 0;i < n;i++){
            while(j > 0 && text[i] != pattern[j])
                j = pm[j-1];
            if(text[i] == pattern[j]) j++;
            if(j == m)
                return i-j+1;
        }
        return -1;
    }
};

相关文章:

  • uv vs pip 速度实测
  • ENSP学习day12
  • aws(学习笔记第三十七课) lambda调用rekognition(名人视频分析)
  • PHY——LAN8720A 寄存器读写 (二)
  • 前向扩散公式推导细节
  • Matlab自学笔记四十九:类型识别:判断数据的类型和类别
  • 2025/3/20 心得
  • HCIA—— 31 HTTP的报文、请求响应报文、方法、URI和URL
  • 【数据标准】数据标准化框架体系-基础类数据标准
  • 基于Real-Sim-Real循环框架的机器人策略迁移方法
  • react拖拽库dnd-kit
  • 【jQuery】插件
  • 【C++初阶】----模板初阶
  • Flask登录页面后点击按钮在远程CentOS上自动执行一条命令
  • 极速版:栈的内存/局部变量表/堆的内存细分
  • 从 select 到 epoll:拆解 I/O 多路复用的演进与实战
  • Teleport场景及原理
  • Python给对象数组排序
  • J2EE框架技术第七章 反射机制与设计模式
  • 什么是大数据
  • 坑梓网站建设流程/高质量发展服务业
  • wordpress阿里秀模板/搜狗排名优化工具
  • 2017网站建设报价方案/百度搜索图片
  • 做网站的软件是是什么/百度应用宝
  • 做的比较好的手机网站/谷歌搜索引擎入口2022
  • 淄博网站建设公司/站长之家关键词查询