Problem
Implement strStr().
Return the index of the first occurrence of needle in haystack, or -1 if needle is not part of haystack.
Example 1:
1 |
|
Example 2:
1 |
|
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().
Explanation
-
We need to find out the beinning index of the
haystack
that matches theneedle
. So, we loop through thehaystack
, and compare its character withneedle
. If the first character ofneedle
matches, we need to compare the second character ofneedle
, and so on. It means we also need to loop through theneedle
. -
To keeping track the beinning index of the
haystack
, we use variablei
. Once the first character ofneedle
matches, we need to check the second character ofneedle
, so how do we access the second character ofhaystack
? We can usei+j
wherej
is the loop index ofneedle
,i
is the loop index ofhaystack
. If the character not match, we just start the next character ofhaystack
and restart thej
to 0, the index ofneedle
. If match andj
is at the end ofneedle
, we can returni
.
Solution
1 |
|