【算法学习记录-散列】【PAT A1084】Broken Keyboard
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.
Sample Input:
7_This_is_a_test
_hs_s_a_es
Sample Output:
7TI
题意:
键盘坏了, 有的字母打不出。
输入两行字符串,第一行为欲输入字符串,第二行为实际显示的字符串。
(包括A-Z,a-z.0-9,以及下划线“_”,字符串长度不超过80)
输出坏掉的按键(①字母全转大写②一个字符只输出一次)。
思路:
0、算法选择
由于题目限定了字符串长度不会超过80,且给出的内存空间足够大,所以其实并不需要使用散列结构及其算法,只用两重for循环即可。
1、整体思路
外层for循环遍历:欲输入的字符串str1
内层for循环遍历:实际输出的字符串str2
if判断str1中的每个字符是否在str2中有相同的,如果有则打印输出
1 int main() { 2 for (int i = 0; i < len1; i++) { 3 c1 = str1[i]; 4 for (int j = 0; j < len2; j++) { 5 c2 = str2[j]; 6 if (c1 == c2) { 7 printf("%c", c1); 8 } 9 } 10 } 11 return 0; 12 }
2、细节处理
①如何比较大小写字母的异同?
比较前,先将小写字母全转为大写
if (c1 >= 'a' && c1 <= 'z') { c1 -= 32; } if (c2 >= 'a' && c2 <= 'z') { c2 -= 32; }
②如何确保每个字符只输出一次?
使用bool hashTable[128],开到128是为了保证a-z A-Z 0-9 _ 对应的ASCII码都能对应于数组下标
从而,若某字符输出过,则该下标对应的元素值改为true
1 bool hashTable[128] = {false}; 2 if (hashTable[c1] == false) { 3 printf("%c", c1); 4 hashTable[c1] = true; 5 }
③将以上综合起来,似乎就变成了
if (c1 == c2 && hashTable[c1] == false) { printf("%c", c1); hashTable[c1] = true; }
但这时输出的是“键盘上没有坏掉的按键”!
因此需要添加条件:j == len2
即“遍历完实际输出的所有字符后,都没有找到与欲输入字符串中的该字符相同的字符”,也就是坏掉的字符按键
3、题解代码
1 #include<iostream> 2 #include<cstdio> 3 #include<cstring> 4 using namespace std; 5 6 int main() { 7 8 char str1[100], str2[100]; 9 cin>>str1; 10 cin>>str2; 11 int len1 = strlen(str1); 12 int len2 = strlen(str2); 13 14 bool hashTable[128] = {false}; 15 char c1, c2; 16 17 for (int i = 0; i < len1; i++) { 18 19 int j; 20 c1 = str1[i]; 21 22 for (j = 0; j < len2; j++) { 23 24 c2 = str2[j]; 25 26 if (c1 >= 'a' && c1 <= 'z') { 27 c1 -= 32; 28 } 29 if (c2 >= 'a' && c2 <= 'z') { 30 c2 -= 32; 31 } 32 if (c1 == c2) { 33 break; 34 } 35 } 36 37 if (j == len2 && hashTable[c1] == false) { 38 printf("%c", c1); 39 hashTable[c1] = true; 40 } 41 } 42 43 return 0; 44 45 }
4、额外要注意的事
PAT的编译器是禁用gets方法的,所以《算法笔记》对该题的解答有错
解决办法是包含iostream库,并using namespace std,再使用cin>>来读入字符串
浙公网安备 33010602011771号