PAT (Basic Level) Practice 1033

1033 旧键盘打字(20)(20 分)

旧键盘上坏了几个键,于是在敲一段文字的时候,对应的字符就不会出现。现在给出应该输入的一段文字、以及坏掉的那些键,打出的结果文字会是怎样?

输入格式:

输入在2行中分别给出坏掉的那些键、以及应该输入的文字。其中对应英文字母的坏键以大写给出;每段文字是不超过10^5^个字符的串。可用的字符包括字母[a-z, A-Z]、数字0-9、以及下划线“_”(代表空格)、“,”、“.”、“-”、“+”(代表上档键)。题目保证第2行输入的文字串非空。

注意:如果上档键坏掉了,那么大写的英文字母无法被打出。

输出格式:

在一行中输出能够被打出的结果文字。如果没有一个字符能被打出,则输出空行。

输入样例:

7+IE.
7_This_is_a_test.

输出样例:

_hs_s_a_tst

分析:题目本身思路不难,就是运用先打Hash表,然后替换字符串。不过有几个点需要注意:

1.输入坏掉的键应当使用getline(),防止输入为空串;

2.此处替换使用std::string::replace()。若在循环体内完成替换,每次替换完毕后应当使下标i--,防止漏掉因为替换而改变位置的字符。

代码:

#include<iostream>
#include<string>
using namespace std;
int hashTable[150] = { 0 };
int main() {
	//freopen("D:\\算法笔记\\例题\\PAT\\input.txt", "r", stdin);
	string brokenKeys;
	//cin >> brokenKeys;
	getline(cin, brokenKeys);
	for (int i = 0; i < brokenKeys.size(); i++) {
		hashTable[brokenKeys[i]] = 1;
		if (brokenKeys[i] >= 'A' && brokenKeys[i] <= 'Z') {
			hashTable[brokenKeys[i] + 32] = 1;
		}
	}
	//getchar();
	string s;
	cin >> s;
	//for (int i = 0; i < s.size(); i++) {
	//	if (hashTable['+'] == 1 && s[i] >= 'A' && s[i] <= 'Z') {
	//		s.replace(i, 1, "");
	//	}
	//	if (hashTable[s[i]] == 1) {
	//		s.replace(i, 1, "");
	//	}
	//}
	for (int i = 0; i < s.size(); i++) {
		if (hashTable['+'] == 1 && s[i] >= 'A' && s[i] <= 'Z') {
			s.replace(i, 1, "");
			i--;
		}
		if (hashTable[s[i]] == 1) {
			s.replace(i, 1, "");
			i--;
		}
	}
	cout << s << endl;
	return 0;
}

猜你喜欢

转载自blog.csdn.net/g28_gwf/article/details/81294970
今日推荐