1.串的定义
2.案例引入
3.串的类型定义,存储结构及其运算
串的存储结构
串的模式匹配算法
int BF_Find(string& s,string& t)
{
int i=0,j=0,index =0;
while(i<s.size() && j<t.size())
{
if (s[i] == t[j])
{
i++;
j++;
} else
{
index++;
i = index;
j=0;
}
}
if(j>=t.size())
{
return index+1;
}
else
{
return 0;
}
}
int main(){
string s1 = "ababababbbb";
string s2 = "abbb";
int pos = BF_Find(s1,s2);
cout << pos <<endl;
}
KMP算法
next是几,就和第几位的比较。
#include <iostream>
#include <string>
using namespace std;
#include "circle.h"
#include "point.h"
#include <windows.h>
#include "vector"
int BF_Find(string& s,string& t)
{
int i=0,j=0,index =0;
while(i<s.size() && j<t.size())
{
if (s[i] == t[j])
{
i++;
j++;
} else
{
index++;
i = index;
j=0;
}
}
if(j>=t.size())
{
return index;
}
else
{
return 0;
}
}
//这种实现是next数组整体右移的情况
void getNext2(vector<int> &next, string t){
//i指向后缀末尾位置
//j指向前缀末尾位置,j也同时代表长度
int i = 0;
int j = -1;
int tLen = t.size();
// cout << t.size() << t.length() <<endl;
next[0] = -1;
while(i<tLen-1){
if (j<0 || t[i] == t[j]){// 初始或找到相同的前后缀
j++;
i++;
next[i] = j;
}
else
{// 前后缀不相同了
j = next[j];
}
}
}
int KMP_Find(string s,string t)
{
int i=0;
int j=0;
int sLen = s.size();
int tLen = t.size();
vector<int> next(tLen);
getNext2(next,t);
while(i<sLen && j<tLen)
{
if (j<0 || s[i] == t[j])// 若匹配,或t已移出最左侧
{
i++;
j++;
} else
{
j = next[j]; // 和BF算法的区别在此
}
}
if(j>=tLen)
{
return i-tLen;
}
else
{
return 0;
}
}
int main(){
string s1 = "hello";
string s2 = "ll";
int pos = BF_Find(s1,s2);
int pos2 = KMP_Find(s1,s2);
cout << pos <<endl;
cout << pos2 <<endl;
}
4.数组
数组的抽象类型定义
数组的顺序存储结构
5.广义表