kmp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
class Match
{
public:
	Match(): repos(NULL){}
	Match(const string& main, const string& mod) 
		:repos(new int[mod.size()]), m_main(main), m_mod(mod)
	{}
 
	~Match()
	{
		delete [] repos;
	}
 
	//~ kmp搜索,默认从主串0位置处开始,
	//~ 匹配成功返回匹配开始的索引,否则返回-1
	int strkmp(size_t pos = 0);
 
	//~ 重设主串与模式串
	void reset(const string& main, const string& mod);
 
private:
	int * repos;
	string m_main; //~ 主串
	string m_mod; //~ 模式串
 
	//~ 生成重定位的索引值
	void gen_rps();
 
};
 
void Match::gen_rps()
{
	repos[0] = -1;
	int i = 0, j = -1;
	while(i < (int)m_mod.size()-1)
	{
		if( j == -1 || m_mod[i] == m_mod[j])
		{
			++i;++j;
			repos[i] = j;
		}
		else
			j = repos[j];
	}
}
 
int Match::strkmp(size_t pos)
{
	gen_rps();
	int i = (int)pos, j = 0;
	while(i < (int)m_main.size() && j < (int)m_mod.size())
	{
		if(j == -1 || m_main[i] == m_mod[j])
		{
			++i;++j;
		}
		else
			j = repos[j];
	}
	if(j == m_mod.size())
		return  i - (int)m_mod.size();
	else 
		return -1;
}
 
void Match::reset(const string& main, const string& mod) 
{
	// ~Match();  为什么不让我显式调用析构函数
	delete [] repos;
	m_main = main; 
	m_mod = mod;
	repos = new int[mod.size()];
}
 
int main()
{
	Match match("acabaabaabcacaabc", "abaabcac");
	cout<<match.strkmp(3)<<endl;
	return 0;
}
Tags: .
你好!除了代码,此处没有多少原创之物,皆为本人搜集、整理、总结之记录与心得,欢迎转载分享!转载时请尽量注明出处,将不胜感激。祝你健康、快乐!
Home

RFC: Request For Comments. Orz..

Name(required)
Mail (required),(will not be published)

RFC: Request For Comments. Orz..

Website(recommended)