字符串匹配问题

Brute Force算法

比较简单好理解

#include <iostream>

int match(char *s, char *t);

int main()
{
	char str_s[7] = "aaaaab";
	char str_t[5] = "aaab";
	int result = match(str_s, str_t);
	if(result >= 0)
		std::cout << "match: " << result << std::endl;
	else
		std::cout << "not match!\n";
	return 0;
}

int match(char *s, char *t)
{
	// i为s的index,j为t的index,初始化为0
	// 当s[i]=t[j]时,i++,j++,否则i回溯到i-j+1, j回溯为0
	// 直到j为t.lenth()+1,match成功,返回i-j
	int i = 0, j = 0;
	while(t[j] != '\0' && s[i] != '\0')
	{
		if(s[i] == t[j])
		{
			i++;
			j++;
		}
		else
		{
			i = i-j+1;
			j = 0;
		} 
	}  
	if(t[j] == '\0')
		return i-j;
	else
		return -1;
}

 

 

KMP算法有点复杂,我也是看了两三遍才看懂在干嘛。。

最后写完发现求 next 数组的方法跟书上不太一样,但书上写的不知道怎么求的

#include <iostream>
#include <string.h>

int match(char *s, char *t);
void next_cal(char *t, int *n);

int main()
{
	char str_s[10] = "aaabaaaab";
	char str_t[6] = "aaaab";
	int result = match(str_s, str_t);
	if(result >= 0)
		std::cout << "match: " << result << std::endl;
	else
		std::cout << "not match!\n";
	return 0;
}

int match(char *s, char *t)
{
	// 先求出字符串t的next数组
	// i为s的index,j为t的index,均初始化为0,s[i] == s[j] 时i++,j++,否则 j=next[j],继续比较
	// j为t.lenth()+1时匹配成功,返回i-j的值,否则返回-1
	if(!strlen(s) || !strlen(t))
		return -1;
	int next[strlen(t)];
	next_cal(t, next); 
//	for(int i = 0; i < strlen(t); i++)
//		std::cout << next[i] << " ";
	int i = 0, j = 0;
	int len_t = strlen(t);
	int len_s = strlen(s);
//	while(j < strlen(t) && i < strlen(s))  //没明白为啥这种写法j=-1的时候会跳出循环。。谁知道可以告诉我一下。。
	while(j < len_t && i < len_s)
	{
		if(j == -1 || s[i] == t[j])
		{
			i++;
			j++;
		}
		else
			j = next[j];
		std::cout << i << " " << j << std::endl;
		
	}  
	if(t[j] == '\0')
		return i-j;
	else
		return -1;
}

void next_cal(char *t, int *n)
{
	n[0] = -1;
	n[1] = 0;
	int j,c,d;
	bool find;
	if(strlen(t) > 2)
	{
		for(int i = 2; i < strlen(t); i++)
		{
			for(j = i-1; j > 0; j--)
			{
				find = false;
				c = j-1;
				d = i-1;
				while(c >= 0)
				{
					if(t[c] == t[d])
					{
						c--;d--;
					}
					else
						break;
				}
				if(c < 0)
				{
					find = true;
					break;
				}
					
			}
			if(find)
			{
				n[i] = j;
			}
			else
				n[i] = 0;
		}
	}
}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值