Skip to content
On this page

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

标签:双指针 字符串 字符串匹配

题目信息

题目地址找出字符串中第一个匹配项的下标

题目内容:

javascript
给你两个字符串haystack和needle

请你在haystack字符串中找出needle字符串的第一个匹配项的下标(下标从0开始)。

如果needle不是haystack的一部分,则返回-1

示例 1
  输入:haystack = "sadbutsad", needle = "sad"
  输出:0
  解释:"sad" 在下标 06 处匹配。
  第一个匹配项的下标是 0 ,所以返回 0

示例 2
  输入:haystack = "leetcode", needle = "leeto"
  输出:-1
  解释:"leeto" 没有在 "leetcode" 中出现,所以返回 -1

提示:
  1 <= haystack.length, needle.length <= 104
  haystack 和 needle 仅由小写英文字符组成

题解

解法一

思路:

直接使用indexOf来获取索引

代码实现:

javascript
/**
 * @param {string} haystack
 * @param {string} needle
 * @return {number}
 */
var strStr = function(haystack, needle) {
    return haystack.indexOf(needle)
};

解法二

思路:

从零开始遍历haystack字符串,设置初始遍历索引idx0

idx <= haystack.length - needle.length时,从haystack中截取needle字符串长度的子串,然后判断该子串和needle是否相等

如果相等就返回索引idx,如果不相等,就将idx + 1然后继续遍历

如果遍历完成后还没找到needle,就返回-1

代码实现:

javascript
/**
 * @param {string} haystack
 * @param {string} needle
 * @return {number}
 */
var strStr = function(haystack, needle) {
    // 如果haystack中不包含needle,直接返回-1
    if(!~haystack.indexOf(needle)) return -1
    // 如果两个字符串相等就直接返回
    if(haystack === needle) return 0
    const hayStackLen = haystack.length
    const needleLen = needle.length
    let idx = 0
    while(idx <= hayStackLen - needleLen) {
        const curStr = haystack.slice(idx, needleLen + idx)
        if(curStr === needle) return idx
        idx += 1
    }
    return -1
};