sayhitrue

  博客园  :: 首页  :: 新随笔  :: 联系 :: 订阅 订阅  :: 管理

时间限制:1000ms
单点时限:1000ms
内存限制:256MB
描述:
fjxmlhx每天都在被沼跃鱼刷屏,因此他急切的找到了你希望你写一个程序屏蔽所有句子中的沼跃鱼(“marshtomp”,不区分大小写)。为了使句子不缺少成分,统一换成 “fjxmlhx” 。

输入
输入包括多行。

每行是一个字符串,长度不超过200。

一行的末尾与下一行的开头没有关系。

输出
输出包含多行,为输入按照描述中变换的结果。

样例输入

The Marshtomp has seen it all before.
marshTomp is beaten by fjxmlhx!
AmarshtompB

样例输出

The fjxmlhx has seen it all before.
fjxmlhx is beaten by fjxmlhx!
AfjxmlhxB

下面的代码用了KMP字符串匹配算法,注意点就是要从后往前替换字符串。

#include<iostream>
#include <string>
#include <vector>
#include<algorithm>
using namespace std;
void preFix(const string &sp, vector<int> &a)
{
	int m = sp.length(), k = 0;
	a[0] = 0;
	for (int q = 1; q < m; ++q)
	{
		while (k>0 && sp[k] != sp[q])
			k = a[k - 1];
		if (sp[k] == sp[q])
			k++;
		a[q] = k;
	}
}
void kmpMatcher(const string &st, const string &sp, vector<int> &a)
{
	int n = st.length(), m = sp.length(), q = 0;
	vector<int> r(m);
	preFix(sp, r);
	for (int i = 0; i < n; ++i)
	{
		while (q>0 && st[i] != sp[q])
			q = r[q - 1];
		if (st[i] == sp[q])
			q++;
		if (q == m)
		{
			a.push_back(i - m + 1);
			q = r[q - 1];
		}
	}
}
int main()
{
	string str, s_c{ "fjxmlhx" }, pattern{"marshtomp"};
	vector<int> pos;
	vector<string> op;
	while (getline(cin, str))
	{
		string lowstr(str);
		pos.clear();
		for (auto &c : lowstr)
			c = tolower(c);
		kmpMatcher(lowstr, pattern, pos);
		for (int i = pos.size() - 1; i >= 0; --i)//要从后往前替换字符串
			str.replace(pos[i], pattern.length(), s_c);
		op.push_back(str);

	}
	for (auto s : op)
		cout << s << endl;
}
posted on 2016-04-09 16:51  sayhitrue  阅读(120)  评论(0编辑  收藏  举报