28. Implement strStr()
Question:
Implement strStr().
Return the index of the first occurrence of needle in haystack, or -1 if needle is not part of haystack.
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().
Example:
Input: haystack = "hello", needle = "ll"
Output: 2
Input: haystack = "aaaaa", needle = "bba"
Output: -1
Input: haystack = "", needle = ""
Output: 0
Source code
Version 1
Idea:
My bad method got Time Limit Exceeded. Because I used two loop to check each characters of string, record the index by 2 variables if both of characters are equal.
I racked my brains for good solution without using substr(). Finally, I got up and went to online to find answer. I refered to Huahua's Tech Road. The loop repeats haystack.length() - needle.length()
times, it can reduce computing time. Use the length of needle to match haystack, if index of j is equal to needle.length(), return index of i.
Time complexity: O(m*n)
Space complexity: O(1)
1 | class Solution { |
Version 2
Idea:
Use KMP algorithm to match two strings that can reduce time complexity.
Time complexity: O(m + n)
// m: match's time; n: generate pi table Space complexity: O(n) // n: the number of elements in pi table
1 | class Solution { |