问题描述:
Implement 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)
{
size_t hay = strlen(haystack);
size_t nee = strlen(needle);
if(nee==0)
return 0;
if(hay==0 || hay<nee)
return -1;
size_t i = 0;
for(size_t j = 0; j < hay; j++)
{
if(needle[i] == haystack[j])
{
i++;
}
else
{
j = j-i;
i = 0;
}
if(i == nee)
{
return j-i+1;
break;
}
}
return -1;
}
};