题目描述
实现 strStr() 函数。
给定一个 haystack 字符串和一个 needle 字符串,在 haystack 字符串中找出 needle 字符串出现的第一个位置
(从0开始)。如果不存在,则返回 -1。
示例一:
输入: haystack = “hello”, needle = “ll”
输出: 2
示例二:
输入: haystack = “aaaaa”, needle = “bba”
输出: -1
js代码:
/**
* @param {string} haystack
* @param {string} needle
* @return {number}
*/
var strStr = function(haystack, needle) {
if(!needle || needle.length <1){return 0}
if(needle.length > haystack.length){
return -1;
}
let subStr = '';
for(let i=0,len=haystack.length;i<len;i++){
if(haystack[i] === needle[0]){
subStr = haystack.substr(i,needle.length);
if(subStr == needle){
return i;
}
}
}
return -1;
};
运行结果: