嗯...为了找工作&提高编程能力,从今天要开始继续做算法题了,一天一道吧!
第一天,偷个懒,做个简单的题目.
题目
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
思路
-暴力解法: 就是从头开始遍历haystack, 然后每个都和needle匹配一次,假如匹配到needle的最后一个index,那就是成功了.返回i(开始的序号)否则返回-1
解法(暴力破解)明天更新kmp算法版
var strStr = function(haystack, needle) {for (let i=0; i <= haystack.length - needle.length; i++){var flag=true;for (let j=0; j < needle.length; j++){if(haystack[i+j] != needle[j]){flag=false;break;}}if(flag)return i;}return -1;
};