code.ashish.me

Atom feed

Recently added: 02 Count Of Subset Sum, 416 Partition Equal Subset Sum, 01 Subset Sum, 518 Coin Change 2, 983 Minimum Cost For Tickets

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