Implement strStr()

Implement strStr().

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

Example 1:

Input:
 haystack = "hello", needle = "ll"

Output:
 2

Example 2:

Input:
 haystack = "aaaaa", needle = "bba"

Output:
 -1

Clarification:

What should we return whenneedleis an empty string? This is a great question to ask during an interview.

For the purpose of this problem, we will return 0 whenneedleis an empty string. This is consistent to C's strstr() and Java's indexOf().

Analysis

字符串匹配问题,直觉的实现就是以needle为pattern string,在haystrack循环遍历0, ..., n - m + 1, 若找到对应则返回index。

O(n^2) time, O(1) space

KMP算法

Solution

Two loops

Use needle as pattern string, outer loop move n - m + 1 times, inner loop at most m times

Multiple Pointers - O(mn) time

Using string equals

Last updated

Was this helpful?