最長公共子串(LCS)與字符串匹配代碼實現

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;
}



發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章