就硬暴力,暴力中的暴力,匹配到对不上的直接从这次匹配到的开头下标+1重匹。
class Solution {
public:
int strStr(string haystack, string needle)
{
if (needle.empty())
{
return 0;
}
int j = 0, i = 0;
while (j < needle.size() && i < haystack.size())
{
if (haystack[i] != needle[j])
{
if (j != 0)
{
i -= j;
}
j = 0;
}
else
{
j++;
}
i++;
}
if (j == needle.size())
{
return i - needle.size();
}
return -1;
}
};