28_Implement strStr()
[Easy]
Return the index of the first occurrence of needle in haystack, or -1 if needle is not part of haystack.
Example 1
Example 2
Example 3 (need to pay attention)
Example 4 (need to pay attention)
Example 5 (need to pay attention)
Example 6 (need to pay attention)
Solution 1: Sliding Window 滑动窗口
Idea:
This is a clean brute-force algorithm. We can traverse all the possible starting points of
haystack
(from0
to
haystack.length() - needle.length()
) and see if the following characters in haystack
match those of needle
.
Special cases:
Both
haystack
andneedle
can be empty. Ifhaystack
is empty,needle
is not, should return-1
. Ifneedle
is empty,haystack
is not, should return0
. If both empty, should return0
.
Time complexity: , where k
is the number of characters in needle.
Code 1:
Code 2:
Last updated