Implement strStr()
Returns the index of the first occurrence of needle in haystack, or -1 if needle is not part of haystack.
实现判断子串的函数,最经典的是KMP算法,但是这个算法实现起来比较复杂,但是确实时间复杂度方面最优的。下面实现了一个简单的算法,也就是需要判断(n-m)*m次, m和n分别为两个字符串的大小, n>m。c++代码如下:
class Solution {
public:
int strStr(char *haystack, char *needle) {
if (!haystack || !needle)
return -1;
int n = strlen(haystack);
int m = strlen(needle);
for (int i = 0; i <= n - m; i++)
{
int j=0;
for (; j<m; j++)
{
if (needle[j] != haystack[j + i])
break;
}
if (j == m)
return i;
}
return -1;
}
};