Skip to content

Latest commit

 

History

History
34 lines (29 loc) · 691 Bytes

28.implement-strstr.md

File metadata and controls

34 lines (29 loc) · 691 Bytes

实现strStr()

题目

思路

直接将haystack字符串按needle字符串进行split, 长度大于1, 则返回数组里第一个字符串的长度即可, 或者直接用indexOf方法.

/**
 * @param {string} haystack
 * @param {string} needle
 * @return {number}
 */
var strStr = function(haystack, needle) {
  if (needle === '') return 0
  const tmp = haystack.split(needle)
  if (tmp.length > 1) {
    return tmp[0].length
  }
  return -1
};
/**
 * @param {string} haystack
 * @param {string} needle
 * @return {number}
 */
var strStr = function(haystack, needle) {
  return haystack.indexOf(needle)
};