Leetcode 28. Implement strStr() (Easy) (cpp)
Tag: Two Pointers, String
Difficulty: Easy
/*
28. Implement strStr() (Easy)
Implement strStr().
Returns the index of the first occurrence of needle in haystack, or -1 if needle is not part of haystack.
*/
class Solution {
public:
int strStr(string haystack, string needle) {
int haylen = haystack.length(), neelen = needle.length();
for (int i = 0, j; i <= haylen - neelen; i++) {
for (j = 0; j < neelen && haystack[i + j] == needle[j]; j++) {
}
if (j == neelen) return i;
}
return -1;
}
};