Leetcode No.28 Implement strStr()字符串匹配(c++实现)
1. 题目
1.1 英文题目
Implement strStr().
Return the index of the first occurrence of needle in haystack, or -1 if needle is not part of haystack.
Clarification:
What should we return when needle is an empty string? This is a great question to ask during an interview.
For the purpose of this problem, we will return 0 when needle is an empty string. This is consistent to C's strstr() and Java's indexOf().
1.2 中文题目
给定一个 haystack 字符串和一个 needle 字符串,在 haystack 字符串中找出 needle 字符串出现的第一个位置 (从0开始)。如果不存在,则返回 -1。
1.3输入输出
输入 | 输出 |
---|---|
haystack = "hello", needle = "ll" | 2 |
haystack = "aaaaa", needle = "bba" | -1 |
haystack = "", needle = "" | 0 |
1.4 约束条件
- 0 <= haystack.length, needle.length <= 5 * 104
- haystack and needle consist of only lower-case English characters.
2. 分析
2.1 Brute Force(暴力搜索)算法
class Solution {
public:
int strStr(string haystack, string needle) {
int ans = -1;
if (needle.size() == 0)
ans = 0;
if (haystack.size() >= needle.size())
for (unsigned int i = 0; i <= haystack.size() - needle.size(); i++)
for (unsigned int j = 0; j < needle.size() && haystack[i + j] == needle[j]; j++)
if (j == needle.size() - 1)
ans = i;
return ans;
}
};
2.2 KMP算法
算法解释可参考:
KMP字符串匹配算法2
从头到尾彻底理解KMP
代码如下:
class Solution {
public:
int strStr(string haystack, string needle) {
int m = haystack.size(), n = needle.size();
if (!n) {
return 0;
}
vector<int> lps = kmpProcess(needle);
for (int i = 0, j = 0; i < m;) {
if (haystack[i] == needle[j]) {
i++, j++;
}
if (j == n) {
return i - j;
}
if (i < m && haystack[i] != needle[j]) {
j ? j = lps[j - 1] : i++;
}
}
return -1;
}
private:
vector<int> kmpProcess(string needle) {
int n = needle.size();
vector<int> lps(n, 0);
for (int i = 1, len = 0; i < n;) {
if (needle[i] == needle[len]) {
lps[i++] = ++len;
}
else if (len) {
len = lps[len - 1];
}
else {
lps[i++] = 0;
}
}
return lps;
}
};
代码参考:https://leetcode.com/problems/implement-strstr/discuss/12956/C%2B%2B-Brute-Force-and-KMP
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 如何编写易于单元测试的代码
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
· 地球OL攻略 —— 某应届生求职总结
· 周边上新:园子的第一款马克杯温暖上架
· Open-Sora 2.0 重磅开源!
· 提示词工程——AI应用必不可少的技术
· .NET周刊【3月第1期 2025-03-02】