我报名参加金石计划1期挑战——瓜分10万奖池,这是我的第5篇文章,点击查看活动详情
题目描述
给你两个字符串 haystack 和 needle ,请你在 haystack 字符串中找出 needle 字符串的第一个匹配项的下标(下标从 0 开始)。如果 needle 不是 haystack 的一部分,则返回 -1 。
示例 1:
输入:haystack = "sadbutsad", needle = "sad"
输出:0
解释:"sad" 在下标 0 和 6 处匹配。
第一个匹配项的下标是 0 ,所以返回 0 。
示例 2:
输入:haystack = "leetcode", needle = "leeto"
输出:-1
解释:"leeto" 没有在 "leetcode" 中出现,所以返回 -1 。
提示:
1 <= haystack.length, needle.length <= 104haystack和needle仅由小写英文字符组成
解题思路 —— 字符串 API
相信熟练搬砖的小伙伴看到题目就有思路了,我们直接用 indexOf ,恰巧它就是从头开始查找给定字符串,找到就返回其起始位置,且找不到返回 -1 ,完全就是给这道题设计的。
题解
/**
* @param {string} haystack
* @param {string} needle
* @return {number}
*/
var strStr = function(haystack, needle) {
return haystack.indexOf(needle);
};
解题思路——常规解法
我们从源字符串的每个位置 i 开始,循环判断 [i, i+needle.length] 这个范围组成的字符串是不是和 needle 相同,如果比较的过程中发现不同则说明不是匹配项,直接退出循环,如果循环结束后都没有中途退出循环,则说明 haystack.substring(i, i+needle.length) 与 needle 匹配的上,返回 i ,否则返回 -1 。
题解
/**
* @param {string} haystack
* @param {string} needle
* @return {number}
*/
var strStr = function(haystack, needle) {
const m = haystack.length, n = needle.length;
for(let i=0; i<=m-n; ++i) {
let startH = i, startN = 0;
while(startH < m && startN < n && haystack[startH] === needle[startN]) {
startN++;
startH++;
}
if(startN === n) return i;
}
return -1;
};