GV

GeezerVison

The World Wide Web, restored to 800 pixels of glory.

Home|About|Gaming cabinet|Archives|How it works|Starter sites

On this site

  • LeetCodeJavascript.com
  • Star on GitHub

This view

  • Original page
  • New address

GeezerVison is showing leetcodejavascript.com — #28 - Implement strStr() - LeetCode JavaScript Solutions

Back to all solutions

#28 - Implement strStr()

Easy • View on LeetCode • View on GitHub
String Two Pointers String Matching

Problem Description

Return the index of the first occurrence of needle in haystack, or -1 if needle is not part of haystack.

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().

Solution

/**
 * @param {string} haystack
 * @param {string} needle
 * @return {number}
 */
var strStr = function(haystack, needle) {
  if (!needle) return 0;
  const split = haystack.split(needle);
  return split.length > 1 ? split[0].length : -1;
};
You are visitor 01402520 — GeezerVison does not store the pages you look up.
Best viewed with Netscape Navigator 4.7 or Internet Explorer 6 at 800×600. No cookies required.