Implement strStr().

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

Clarification:

What should we return when needle is an empty string? This is a great question to ask during an interview.

For the purpose of this problem, we will return 0 when needle is an empty string. This is consistent to C's strstr() and Java's indexOf().

 

前几天刚好学了kmp算法,没啥说的,直接套kmp算法,注意needle字符串为空的情况。

/**
 * @param {string} haystack
 * @param {string} needle
 * @return {number}
 */
var strStr = function(haystack, needle) {
  var len1 = haystack.length;
  var len2 = needle.length;
  if(len2==0) return 0;
  var next = [-1,0];
  var i = 0;
  var j = -1;
  while(i < len2-1) {
    if(j === -1 || needle[i] === needle[j]) next[++i] = ++j;
    else j = next[j];
  }
  i = 0, j = 0;
  while(i < len1 && j < len2) {
    if(j === -1 || haystack[i] === needle[j]) i++, j++;
    else j = next[j];
    if(j === len2) return i-j;
  }
  return -1;
};

  

 

posted on 2019-04-09 20:32  promise。  阅读(86)  评论(0编辑  收藏  举报