#include<iostream>
#include<string>
using namespace std;
/**
計算可跳轉字符個數數組
*/
int getDis(string &str,int *dis)
{
int len=str.length();
for (int i = 0; i < 256; i++)
dis[i]=len; //最大跳躍字符數
for (int i = 0; i < len-1; i++) //注意這裏不包括最後一個
dis[str[i]]=len-1-i;
return 0;
}
/**
查找
*/
int search(string &text,string &pattern,int *dis)
{
int j,pos;
bool tag=false;
int lenPattern=pattern.length();
int lenTrext=text.length();
j=0;
pos=0;
while(pos<=lenTrext-lenPattern)
{
j=lenPattern-1;
while(j>=0 && pattern[j]==text[pos+j]) //向前搜索
j--;
if(j==-1)
{
tag=true;
cout<<"The result is :"<<pos<<endl<<endl;
pos=pos+lenPattern;
continue;
}
else
pos=pos+dis[text[pos+lenPattern-1]]; //使用最後一個字符對齊的方法,進行“跳躍”移動
}
if(tag == false) //不存在匹配
cout<<"-1"<<endl<<endl;
return 0;
}
int main()
{
int dis[256];
string text;
string pattern;
while(true)
{
cout<<"文本:";
cin>>text;
cout<<"模式:";
cin>>pattern;
getDis(pattern,dis);
search(text,pattern,dis);
}
return 0;
}
參考鏈接:https://www.cnblogs.com/xudong-bupt/p/3433954.html