最长公共子串(LCS)与字符串匹配代码实现

本文详细介绍了C++中使用动态规划求解最长公共子串问题,并通过实现朴素字符串匹配算法和KMP算法进行字符串匹配。通过具体代码实例,深入探讨了算法原理与应用。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

1. 最长公共子串(LCS)c++代码实现(动态规划算法):

int DP_LCS(const string& text, const string& query)
{
	int len_t = text.length(), len_q = query.length();
	if(len_t == 0 || len_q == 0)
	{
		return 0;
	}
	int *len = new int[len_q + 1];
	for(int i = 0; i <= len_q; ++i)
	{
		len[i] = 0;
	}
	int len_lcs(0);
	for(int i = 0; i < len_t; ++i)
	{
		for(int j = len_q; j > 0; --j)
		{
			if(text[i] == query[j-1])
			{
				len[j] = len[j-1] + 1;
				if(len[j] > len_lcs)
				{
					len_lcs = len[j];
				}
			}
			else
			{
				len[j] = 0;
			}
		}
	}
	delete[] len;
	return len_lcs;
} 

2. 字符串匹配算法:

2.1 朴素的字符串匹配算法:

int naive_str_match(const string& text, const string& query)
{
	int count(0);
	int len_t(text.length()), len_q(query.length());
	if(len_t == 0 || len_q == 0)
	{
		return 0;
	}
	for(int i = 0; i < len_t; ++i)
	{
		int j(0);
		while(j < len_q && query[j] == text[i+j])
		{
			++j;
		}
		if(j == len_q)
		{
			++count;
			cout << "find query at " << i << endl;
		}
	}
	return count;
}

2.2 KMP算法:

void compute_prefix_function(int *p, const string& query) // p[k]: max length of prefix(q[k]) witch is also postfix of q[k] 
{
	p[0] = 0;
	int k(0), len_q(query.length());
	for(int i = 1; i < len_q; ++i)
	{
		while(k > 0 && query[k] != query[i])
		{
			k = p[k];
		}
		if(query[k] == query[i])
		{
			++k;
		}
		p[i] = k;
	}
}
int KMP_Method(const string& text, const string& query)
{
	int len_t(text.length()), len_q(query.length());
	if(len_t == 0 || len_q == 0)
	{
		return 0;
	}
	int count(0);
	int *p = new int[len_q];
	compute_prefix_function(p, query);
	
	int q(0);
	for(int i = 0; i < len_t; ++i)
	{
		while(q > 0 && text[i] != query[q])
		{
			q = p[q-1];
		}
		if(text[i] == query[q])
		{
			if(++q == len_q)
			{
				cout << "find match at " << i-q+1 << endl;
				++count;
				q = p[q-1];
			}
		}
	}
	delete[] p;
	return count;
}

3.测试:

#include <iostream>
#include <string>
using namespace std;

int main(int argc, char** argv) {
	string text("abacdac");
	string query("a");
	cout << naive_str_match(text, query) << endl;
	cout << KMP_Method(text, query) << endl;
	return 0;
}



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值