问题描述
从文本串t中找出第一次模式串p出现的位置
1.暴力穷举
思路如下图所示:
https://pic4.zhimg.com/v2-817073ca77f6c75d234392f207a3c81b_b.webp
#include <iostream>
#include <string.h>
using namespace std;
int find(string haystack, string needle)
{
int t = haystack.size();
int p = needle.size();
int i=0;
int j=0;
while(i<t && j<p) //
{
if(haystack[i+j] == needle[j]) //如果匹配则j指针右移
j++;
else //一旦发生不匹配的情况,则i指针向右移动一格,且j回溯到0
{
i++;
j=0;
}
}
if(j>=p) return i; //如果j到达末尾,就说明完全匹配了,这时返回指针i
return -1;
}
int main(){
string s1 = "hellow";
string s2 = "ll";
cout<<find(s1,s2)<<endl;
return 0;
}
2.KMP算法