嗯...爲了找工做&提升編程能力,從今天要開始繼續作算法題了,一天一道吧!
第一天,偷個懶,作個簡單的題目.算法
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; };