栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > C/C++/C#

【C语言数据结构】字符串

C/C++/C# 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

【C语言数据结构】字符串


文章目录
  • TOP0、BF算法
  • 一、KMP算法
  • 二、图解与分析


TOP0、BF算法
#include 
#include 
#include 

typedef struct {
	char *ch;
	int len;
}SString;

int MAXSIZE = 10;
int bf(SString s, SString t); 

int bf(SString s, SString t) {
	int i = 1, j = 1;
	while ( i <= s.len && j <= t.len) {
		if (s.ch[i] == t.ch[j]) {	
			i ++;
			j ++;
		} else {
			i = i - j + 2;
			j = 1;
		}
	}
	if ( j > t.len ) return i - t.len;
	return 0; 
}

int main() {
	SString s, t;
	s.ch = (char *)malloc(MAXSIZE * sizeof(char));
	s.ch ++;
	t.ch = (char *)malloc(MAXSIZE * sizeof(char));
	t.ch ++;
	printf("请输入一个主串:");
	scanf("%s", s.ch);
	s.len = strlen(s.ch);
	printf("请输入一个子串:");
	scanf("%s", t.ch);
	t.len = strlen(t.ch);
	s.ch --;
	t.ch --;
	int result;
	result = bf(s, t);
	printf("%dn", result);
	
	free(s.ch);
	free(t.ch);
	return 0;
}
一、KMP算法
#include 
#include 
#include 

typedef struct {
	char *ch;
	int len;
}SString;

int MAXSIZE = 10;
void next(SString t, int next[]);
int Index_KMP(SString s, SString t, int next[]); 

// 求next数组 
void get_next(SString t, int next[]) {
	int i = 1, j = 0;
	next[i] = 0;
	while ( i < t.len) {
		if (j == 0 || t.ch[i] == t.ch[j]) {
			i ++;
			j ++;
			next[i] = j;
		} else {
			j = next[j];
		}
	}
}

// kmp 
int Index_KMP(SString s, SString t, int next[]) {
	int i = 1, j = 1;
	while( i <= s.len && j <= t.len) {
		if (j == 0 || s.ch[i] == t.ch[j] ) {
			j ++;
			i ++;
		} else {
			j = next[j];
		}
	} 
	if ( j > t.len) return i - t.len;
	else return 0;
} 

int main() {
	SString s, t;
	s.ch = (char *)malloc(MAXSIZE * sizeof(char));
	s.ch ++;
	t.ch = (char *)malloc(MAXSIZE * sizeof(char));
	t.ch ++;
	printf("请输入一个主串:");
	scanf("%s", s.ch);
	s.len = strlen(s.ch);
	printf("请输入一个子串:");
	scanf("%s", t.ch);
	t.len = strlen(t.ch);
	s.ch --;
	t.ch --;
	// 求next 
	int next[t.len + 1];
	get_next(t, next);
	// KMP算法
	int result;
	result = Index_KMP(s, t, next);
	printf("%d ", result); 
	free(s.ch);
	free(t.ch);
	return 0;
}
二、图解与分析

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/890416.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号