king-lxt / LeetCode-javasctipt

leetCode 答案
0 stars 0 forks source link

实现 strStr()---leetcode(28题) #2

Open king-lxt opened 3 years ago

king-lxt commented 3 years ago
实现 strStr() 函数。

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

 

说明:

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

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

输入:haystack = "hello", needle = "ll"
输出:2
king-lxt commented 3 years ago
/**
 * @param {string} haystack
 * @param {string} needle
 * @return {number}
 */
var strStr = function (haystack, needle) {
  if (needle.length === 0 || haystack.length === 0 && needle.length === 0) {
    return 0;
  }
  if (haystack.length === 0) {
    return -1; 
  }
  return haystack.indexOf(needle);
};