题目内容
实现 strStr() 函数。
给定一个 haystack 字符串和一个 needle 字符串,在 haystack 字符串中找出 needle 字符串出现的第一个位置 (从0开始)。如果不存在,则返回 -1。
示例:
输入: haystack = "hello", needle = "ll" 输出: 2
输入: haystack = "aaaaa", needle = "bba" 输出: -1
解法一,indexOf不用白不用
JavaScript中String对象有个叫indexOf
的方法,功能是返回调用它的String对象中第一次出现的指定值的索引。 跟题目要求完美契合。
如果不考虑边界情况,一行代码就可以解决问题。
var strStr = function (haystack, needle) {
if (needle.length === 0) {
return 0
}
if (needle.length > haystack.length) {
return -1
}
return haystack.indexOf(needle)
};