1. 程式人生 > >PAT(Advanced) 1084 Broken Keyboard(20 分)

PAT(Advanced) 1084 Broken Keyboard(20 分)

On a broken keyboard, some of the keys are worn out. So when you type some sentences, the characters corresponding to those keys will not appear on screen.

Now given a string that you are supposed to type, and the string that you actually type out, please list those keys which are for sure worn out.

Input Specification:

Each input file contains one test case. For each case, the 1st line contains the original string, and the 2nd line contains the typed-out string. Each string contains no more than 80 characters which are either English letters [A-Z] (case insensitive), digital numbers [0-9], or _

 (representing the space). It is guaranteed that both strings are non-empty.

Output Specification:

For each test case, print in one line the keys that are worn out, in the order of being detected. The English letters must be capitalized. Each worn out key must be printed once only. It is guaranteed that there is at least one worn out key.

解答:

這道題需要注意的是,字母的大小寫對應於同一個按鍵,比如t和T;

另外在遍歷比較時, 需要對完整字串的後部分進行判定,是否存在缺失按鍵的情況。

AC程式碼如下:

#include<cstdio>
#include<cstring>
#include<cctype>
#include<vector>

using namespace std;

void toUpper(char* s)
{
	int len = strlen(s);
	for(int i = 0; i < len; ++i){
		if( islower(s[i]) ){
			s[i] = toupper(s[i]);
		}
	}	
}

int main()
{
	char full[100], lack[100];
	vector<char> cvec;
	
	scanf("%s %s", full, lack);
	toUpper(full);
	toUpper(lack);
	
	int i = 0, j = 0, len1 = strlen(full), len2 = strlen(lack);
	while(i < len1 && j < len2){
		if(full[i] != lack[j]){
			int k = 0;
			for(; k < cvec.size(); ++k){
				if(full[i] == cvec[k]) break;
			}
			if(k >= cvec.size())
				cvec.push_back(full[i]);
			i++;
		}else{
			i++; j++;
		}
	}
	while(i < len1){
		int k = 0;
		for(; k < cvec.size(); ++k){
			if(full[i] == cvec[k]) break;
		}
		if(k >= cvec.size())
			cvec.push_back(full[i]);
		i++;
	}
	for(int i = 0; i < cvec.size(); ++i){
		printf("%c", cvec[i]);
	}
	printf("\n");
	return 0;
}