LeetCode-28-实现strStr()
in LeetCode with 0 comment

LeetCode-28-实现strStr()

in LeetCode with 0 comment

原题地址:实现strStr()

实现 strStr() 函数。

给定一个 haystack 字符串和一个 needle 字符串,在 haystack 字符串中找出 needle 字符串出现的第一个位置 (从0开始)。如果不存在,则返回  -1

示例 1:

输入: haystack = "hello", needle = "ll"
输出: 2

示例 2:

输入: haystack = "aaaaa", needle = "bba"
输出: -1

说明:

当 needle 是空字符串时,我们应当返回什么值呢?这是一个在面试中很好的问题。

对于本题而言,当 needle 是空字符串时我们应当返回 0 。这与C语言的 strstr() 以及 Java的 indexOf() 定义相符。

暴力匹配

题目的要求就是查找模板串needle在字符串haystack中第一次出现的位置,所以我们可以直接暴力匹配。

两个字符串从开头开始依次匹配,当发现中间某个字符不再匹配时,两个字符串都回到开头,然后haystack前进一步再重新匹配,直到匹配成功或最终发现模板字符串在haystack中不存在为止。

具体的实现代码如下:

/**
 * @param {string} haystack
 * @param {string} needle
 * @return {number}
 */
const strStr1 = function(haystack, needle) {
    if (!needle) {
        return 0;
    }
    for (let i = 0; i < haystack.length - needle.length + 1; i ++) {
        let j = 0;
        while (j < needle.length) {
            if (haystack[i+j] !== needle[j]) { // 字符不匹配
                break;
            }
            j ++;
        }
        // 匹配成功
        if (j === needle.length) {
            return i;
        }
    }
    // needle在haystack中不存在
    return -1;
};

测试:

let start = new Date();
const test = strStr1;
console.log(test('a', 'a')); // 0
console.log(test('hello', 'll')); // 2
console.log(test('aaaaa', 'bba')); // -1
console.log(new Date().getTime() - start.getTime()); // 6

时间复杂度: 最差情况下模板字符串需要与原字符串全部匹配一次,时间复杂度为O((m-n)*n),其中n为模板字符串的长度,m为原字符串的长度
空间复杂度: 常数级的额外空间,空间复杂度为O(1)