//问题:实现strstr函数,子串查找(子串匹配)
//方法一:扫描主串,再扫描子串,O(mn)
#include <string>
class Solution
{
public:
int strStr(string haystack, string needle)
{
int m = haystack.size(), n = needle.size();
if(n == 0) return 0; //如果needle为空
/* int result = haystack.find(needle);
if(result != string::npos) return result;
else return -1;*/
for(int i = 0; i <= m-n; i++) //扫描主串,最后一个位置起始索引为m-n, i = 0~m-n
{
int j =0;
for(; j<n; j++) //扫描子串,j=0~n-1
{
if(haystack[i+j] != needle[j]) break; //如果有某个字符不匹配则退出循环
}
if(j == n) return i; //如果均匹配,返回子串在主串中的起始索引
}
return -1; //如果未找到,则返回-1
}
};
//方法二:KMP算法(子串匹配的更高效算法)