28.Implement strStr()
Example 1:
Input: haystack = "hello", needle = "ll"
Output: 2
Example 2:
Input: haystack = "aaaaa", needle = "bba"
Output: -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().class Solution {
public:
int strStr(string haystack, string needle) {
int n_len=needle.length();
int h_len=haystack.length();
if(n_len==0) return 0;
if(n_len>h_len) return -1;
if(n_len == h_len) return haystack == needle? 0:-1;
for(int i=0;i<h_len-n_len+1;i++)
if(haystack[i] == needle[0] && haystack.substr(i,n_len) == needle) return i;
return -1;
}
};Last updated