178. Find the Index of the First Occurrence in a String

EasyStringString

Given two strings haystack and needle, return the index of the first occurrence of needle in haystack, or -1 if needle is not part of haystack.

If needle is empty, return 0.

Input: Two comma-separated strings: haystack and needle.

Output: An integer — the starting index of needle in haystack, or -1 if not found.

Examples

Example 1
Input: sadbutsad,sad
Output: 0
Explanation: 'sad' first occurs at index 0.
Example 2
Input: leetcode,leeto
Output: -1
Explanation: 'leeto' is not in 'leetcode'.
Example 3
Input: hello,ll
Output: 2
Explanation: 'll' starts at index 2.

Constraints

Asked by

CapgeminiBloombergMicrosoftGoogleAmazonApple
Solve this problem in the editor →