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
haystackthat matches theneedle. So, we loop through thehaystack, and compare its character withneedle. If the first character ofneedlematches, 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 ofneedlematches, we need to check the second character ofneedle, so how do we access the second character ofhaystack? We can usei+jwherejis the loop index ofneedle,iis the loop index ofhaystack. If the character not match, we just start the next character ofhaystackand restart thejto 0, the index ofneedle. If match andjis at the end ofneedle, we can returni. 
Solution
1  |  |