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

leetcode28. 找出字符串中第一个匹配项的下标_简单KMP

 28. 找出字符串中第一个匹配项的下标 - 力扣(LeetCode)

模仿:algorithm-journey/src/class100/Code01_KMP.java at main · algorithmzuo/algorithm-journey · GitHub

#include <stdio.h>
#include <stdlib.h>
#include <string.h>void getNext(char *s, int m, int *next) {if (m == 1) {next[0] = -1;return;}next[0] = -1;next[1] = 0;int i = 2, cn = 0;while (i < m) {if (s[i - 1] == s[cn]) {next[i++] = ++cn;} else if (cn > 0) {cn = next[cn];} else {next[i++] = 0;}}
}int kmp(char *s1, char *s2) {int n = strlen(s1), m = strlen(s2);int x = 0, y = 0;int *next = (int *)malloc(m * sizeof(int));getNext(s2, m, next);while (x < n && y < m) {if (s1[x] == s2[y]) {x++;y++;} else if (y == 0) {x++;} else {y = next[y];}}free(next);return y == m ? x - y : -1;
}int strStr(char *haystack, char *needle) {return kmp(haystack, needle);
}

 官方题解:

C++

class Solution {
public:int strStr(string haystack, string needle) {int n = haystack.size(), m = needle.size();if (m == 0) {return 0;}vector<int> pi(m);for (int i = 1, j = 0; i < m; i++) {while (j > 0 && needle[i] != needle[j]) {j = pi[j - 1];}if (needle[i] == needle[j]) {j++;}pi[i] = j;}for (int i = 0, j = 0; i < n; i++) {while (j > 0 && haystack[i] != needle[j]) {j = pi[j - 1];}if (haystack[i] == needle[j]) {j++;}if (j == m) {return i - m + 1;}}return -1;}
};

C:

int strStr(char* haystack, char* needle) {int n = strlen(haystack), m = strlen(needle);if (m == 0) {return 0;}int pi[m];pi[0] = 0;for (int i = 1, j = 0; i < m; i++) {while (j > 0 && needle[i] != needle[j]) {j = pi[j - 1];}if (needle[i] == needle[j]) {j++;}pi[i] = j;}for (int i = 0, j = 0; i < n; i++) {while (j > 0 && haystack[i] != needle[j]) {j = pi[j - 1];}if (haystack[i] == needle[j]) {j++;}if (j == m) {return i - m + 1;}}return -1;
}

待定

http://www.xdnf.cn/news/1596.html

相关文章:

  • vue3 实现将html内容导出为图片、pdf和word
  • Linux Awk 深度解析:10个生产级自动化与云原生场景
  • 私钥连接服务器(已经有服务器私钥
  • 安卓adb shell串口基础指令
  • 【激光雷达3D(7)】CenterPoint两阶段细化仅使用BEV特征;PV-RCNN两阶段细化使用体素特征;M3DETRTransformer统一多表征特征
  • 云智融合普惠大模型AI,政务服务重构数智化路径
  • 【C语言经典算法实战】:从“移动距离”问题看矩阵坐标计算
  • Python正则表达式:用“模式密码“解锁复杂字符串
  • C++中的next_permutation全排列函数
  • 【高频考点精讲】JavaScript中的组合模式:从树形结构到组件嵌套实战
  • 与终端同居日记:Shell交响曲の终极共舞指南
  • 【玩转全栈】—— Django+vue3+讯飞星火API 实现前端页面实时AI答复
  • C++算法(14):K路归并的最优解法
  • python的pip download命令-2
  • COMSOL多孔结构传热模拟
  • gem5-gpu教程06 回归测试
  • 2025年渗透测试面试题总结-拷打题库13(题目+回答)
  • GPLT-2025年第十届团体程序设计天梯赛总决赛题解(2025天梯赛题解,共计266分)
  • 【LangChain4j】AI 第二弹:项目中接入 LangChain4j
  • QVQ-Max视觉推理模型发布:多模态 AI 的“眼脑协同”革命
  • 详解微服务监控(springboot admin server client、实时日志配置、动态修改日志级别、自定义服务通知实现等
  • 通过智能分块策略、动态分块、多路召回与重排序融合、异构数据关联与溯源提升Ragflow与LangChain提升RAG的召回率
  • HarmonyOS Grid 网格列表可长按 item 拖动移动位置
  • ROS第十二梯:ros-noetic和Anaconda联合使用
  • ProxySQL实现mysql8主从同步读写分离
  • 开启内测!360纳米AI推出“MCP万能工具箱”
  • C# 设计原则总结
  • stack和queue的学习
  • 基于 Windows11 WSL2 的 ESP-IDF V5.4 开发环境搭建教程
  • 如何安装Visio(win10)