题目要求: mplement strStr().
Returns the index of the first occurrence of needle in haystack, or -1 if needle is not part of haystack.
这道题是一个字符匹配问题,可以采用KMP算法。 下面是采用一般方法的解答:
class Solution
{
public:
int strStr(char *haystack, char *needle)
{
int i,j;
for (i = j = 0; haystack[i] && needle[j];) {
if (haystack[i] == needle[j]) {
++i;
++j;
} else {
i = i - j + 1;
j = 0;
}
}
return needle[j] ? -1 : i - j;
}
};