刷leetcode,一题花了不少次,总是会提示有错误的地方,最后看了c++的实现方法,也算是写了出来
Return the index of the first occurrence of needle in haystack, or -1
if needle is not part of haystack.Example 1:
Input: haystack = “hello”, needle = “ll” Output: 2 Example 2:
Input: haystack = “aaaaa”, needle = “bba” Output: -1
/**
* @param {string} haystack
* @param {string} needle
* @return {number}
*/
var strStr = function(haystack, needle) {
if(needle.length==0) return 0;
if(needle.length>haystack.length) return -1;
index=0;
while(index+needle.length<=haystack.length){
for(i=0;i<=needle.length;){
if(i==needle.length) {
return index;
}
if(needle[i]!=haystack[i+index]){
index++;
break;
}
else if(needle[i]==haystack[i+index]){
i++;
}
}
}
return -1;
};
做了这么多的算法题,感觉用到的for循环不是很多,而每次做题,本能第一反应都是用for,感觉需要有所改变了,也要更加完善自己的逻辑思维