code.ashish.me

Atom feed

Recently added: 128 Longest Consecutive Sequence, 347 Top K Frequent Elements, 045 Jump Game 2, 228 Summary Ranges, 219 Contains Duplicate 2

028 Implement Strstr

/**
 *
 * Ashish Patel
 * e: ashishsushilPatel@gmail.com
 * w: https://ashish.me
 *
 */

function strStr(haystack, needle) {
  if (needle === '') return 0
  for (let i in haystack) {
    if (haystack[i] === needle[0] && haystack.substring(i, Number(i) + needle.length) === needle) {
      return Number(i)
    }
  }
  return -1
}

test('implement strStr()', () => {
  expect(strStr('hello', 'll')).toEqual(2)
  expect(strStr('a', 'a')).toEqual(0)
  expect(strStr('aaa', 'aaaa')).toEqual(-1)
  expect(strStr('mississippi', 'issip')).toEqual(4)
})

Created 2020-03-31T21:43:06+00:00 · Edit