【LeetCode】28 - Implement strStr()

时间:2021-09-03 15:56:55

Implement strStr().

Returns the index of the first occurrence of needle in haystack, or -1 if needle is not part of haystack.

Solution: 

 class Solution {
public:
int strStr(string haystack, string needle) { //runtime:4ms
int len1=haystack.size(), len2=needle.size();
for(int i=;i<=len1-len2;i++)
{
int j=;
for(;j<len2;j++){
if(haystack[i+j]!=needle[j])break;
}
if(j==len2)return i;
}
return -;
}
};