数据结构第四章:串

数据结构第四章:串

  • 串定长存储有两种表示方法,一种是第一个元素存储串长,一种是用特殊结束标记字符表示串的结束,该字符不计入串长
  • 串可以有链式存储,每个结点可以存放多个字符,最后一个节点不一定存满,所以最后会补上特殊非串值字符。块链就是一种串的链式存储,块链有三个描述成员,一个是头指针,一个是尾指针,一个是串长。
  • 存储密度 = 串值所占存储位 / 实际分配存储位
  • 串匹配的一种简单算法:
// if failed, return 0
int Index(char[] T, char[] S, int pos)
{
	// T is mode string, S is to be matched, pos is the started position
	int i = pos, j = 1;
	while( i <= S[0] && j <= T[0]) // length of string in first element of char array
	{
		if(S[i]==T[j])
		{
			i++;j++;
		}
		else
		{
			i = i - j + 2;
			j = 1;
		}
	}
	if(j > T[0])
		return i-T[0];
	return 0;
}
  • KMP算法和简单算法的差别在于 i 不再回溯,而 j 也不每次都变为1,会根据next函数来回溯。给定next值后KMP算法如下:
// if failed, return 0
int Index(char[] T, int next[], char[] S, int pos)
{
	// T is mode string, S is to be matched, pos is the started position
	int i = pos, j = 1;
	while( i <= S[0] && j <= T[0]) // length of string in first element of char array
	{
		if(j==0 || S[i]==T[j])
		{
			i++;
			j++;
		}
		else
		{
			j = next[j];
		}
	}
	if(j > T[0])
		return i-T[0];
	return 0;
}
  • 而 next 值的计算方法其实就是对模式串自身进行串匹配
void get_next(char[] T, int next[])
{
	int i = 1, j = 0; // different1 : j = 0 not 1
	next[1] = 0; // init
	while( i < T[0] ) // different2 : not <= but <
	{
		if(j==0 || T[i]==T[j])
		{
			i++;
			j++;
			next[i]=j; //different3 : record next[] here
		}
		else
		{
			j = next[j];
		}
	}
	return;
}

  • 串应用——文本编辑:将文本存储为长字符串,通过建立行表和页表来管理文本。行表存储文本每行起始位置和行长度,若在某行插入或删除字符,则需要修改行长度,若修改后行长度超限,则需要重新分配存储空间,并修改行起始位置;若删除行或添加行,需要同时修改行表和页表,等等。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值