28.找出字符串中第一个匹配项的下标

找出字符串中第一个匹配项的下标

给你两个字符串 haystack 和 needle,请你在 haystack 字符串中找出 needle 字符串的第一个匹配项的下标(下标从 0 开始)。如果 needle 不是 haystack 的一部分,则返回 -1。

示例 1:

输入:haystack = “sadbutsad”, needle = “sad”
输出:0
解释:”sad” 在下标 0 和 6 处匹配。第一个匹配项的下标是 0。

示例 2:

输入:haystack = “leetcode”, needle = “leeto”
输出:-1
解释:”leeto” 没有在 “leetcode” 中出现。

提示:

  • 1 <= haystack.length, needle.length <= $10^4$
  • haystack 和 needle 仅由小写英文字符组成

解析

直接遍历 haystack,逐个位置检查是否与 needle 匹配。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
/**
* @param {string} haystack
* @param {string} needle
* @return {number}
*/
var strStr = function (haystack, needle) {
if (needle.length > haystack.length) return -1;

for (let i = 0; i <= haystack.length - needle.length; i++) {
let matched = true;
for (let j = 0; j < needle.length; j++) {
if (haystack[i + j] !== needle[j]) {
matched = false;
break;
}
}
if (matched) return i;
}
return -1;
};

暴力匹配法,时间复杂度 O(m*n)。也可以使用 KMP 算法将时间复杂度降低到 O(m+n),但对于本题的数据范围,暴力法已经足够。


28.找出字符串中第一个匹配项的下标
https://leetcode.lz5z.com/28.find-the-index-of-the-first-occurrence-in-a-string/
作者
tickli
发布于
2023年8月21日
许可协议