1.串的定义
串是内容受限制的线性表。只能由字符组成。
子串:空串或者任意个连续字符组成的子序列(类比子集),包括其自身
真子串:类比真子集
主串:包含子串的串
字符位置:字符在序列中的序号为该字符在串中的位置(从1开始数)
空格串:由若干个空串组成
串相等:当且仅当长度相等对应位置字符相等(所有空串相等)
2.串的案例
病毒感染检测
病毒为环状(baa,aab,aba)
3.顺序串和链串
//串的顺序存储结构
#define MAXLEN 255
typedef struct {
char ch[MAXLEN + 1];//存储串的一维数组
int length;//串的当前长度
}SString;
//串的链式存储结构-块链结构
#define CHUNKSIZE 80
typedef struct Chunk {
char ch[CHUNKSIZE];
struct Chunk* next;
}Chunk;
typedef struct {
Chunk* head, * tail;//串的头指针和尾指针
int curlen;//串的当前长度
}LString;//字符串的块链结构
4.BF算法
主串回溯
int Index_BF(SString S, SString T) {
int i = 1, j = 1;
while (i <= S.length && j <= T.length) {//两种情况,一种是匹配成功了,另一种是超出了
if (s.ch[i] == t.ch[j]) { ++i; ++j; }
else { i = i - j + 2; j = 1; }
}
if (j >= T.length)return i - T.length;
else return 0;
}
严版的数据结构在BF算法这里做了一个默认, 即默认数组是从1开始而非从0开始。
/*java实现*/
package eg;
public class eg0{
public static void main(String[] args) {
String destString="WHNBWHSXTNB";
String subString="WHSXT";
int index=bfSearch(destString,subString);
System.out.println(index);
}
public static int bfSearch(String destStr,String subStr) {
int x=1;
int y=1;
while(x<destStr.length()&&y<subStr.length()) {
if(destStr.charAt(x)==subStr.charAt(y)) {
x++;
y++;
}
else {
x=x-y+2;
y=1;
}
}
if(y==subStr.length()) {
return x-y+1;
}
else {
return 0;
}
}
}
5.KMP算法
移动子串,寻找j的下一个位置即可
int Index_KMP(SString S, SString T, int pos) {
i = pos, j = 1;
while (i < S.length && j < T.length) {
if (j == 0 || S.ch[i] == T.ch[j]) {
i++;j++
}
else
{
j = next[j];
}
}
if (j > T.length)return i - T.length;
else return 0;
}
you'hua优化:
第一个一定是0,第二个next为1,则与第一个进行比较,a≠b,则直接把b的next值落下。
第三个next为1,则与第一个进行比较,a=a,则把前面a的next值落下
第五个next=2,则与第二个进行比较,b=b,又b的next=1,所以继续与第一个比较,a≠b,则直接把b的落下。
只需要进行一次比较的,若字母相等则落下前面字母的next,若字母不相等则落下本身的next;
需要进行连环比较的,若相等则继续往前比较,若不相等直接落下最后一个相等的本身next。
完整代码实现暂无