嗯...为了找工做&提升编程能力,从今天要开始继续作算法题了,一天一道吧!
第一天,偷个懒,作个简单的题目.算法
Return the index of the first occurrence of needle in haystack, or -1 if needle is not part of haystack.编程
Example 1:code
Input: haystack = "hello", needle = "ll"
Output: 2
Example 2:io
Input: haystack = "aaaaa", needle = "bba"
Output: -1function
-暴力解法: 就是从头开始遍历haystack, 而后每一个都和needle匹配一次,假如匹配到needle的最后一个index,那就是成功了.返回i(开始的序号)不然返回-1遍历
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; };