【算法学习记录-散列】【PAT A1050】String Subtraction
Given two strings S1 and S2, S=S1−S2 is defined to be the remaining string after taking all the characters in S2 from S1. Your task is simply to calculate S1−S2 for any given strings. However, it might not be that simple to do it fast.
Input Specification:
Each input file contains one test case. Each case consists of two lines which gives S1 and S2, respectively. The string lengths of both strings are no more than 1. It is guaranteed that all the characters are visible ASCII codes and white space, and a new line character signals the end of a string.
Output Specification:
For each test case, print S1−S2 in one line.
Sample Input:
They are students.
aeiou
Sample Output:
Thy r stdnts.
思路:
0、题目本身没有难度,“裁剪”字符串本质还是输出和不输出的问题
只是由于PAT禁止使用gets方法读取字符串,所以读的时候会有点小麻烦
1、整体思路
开一个bool类型的visible[128],下标对应每个字符的ASCII码,true和false表示是否输出
分别读入两行字符串
遍历第二行字符串,对应的visible数组中的元素设为false
遍历第一行字符串,并用if判断是否能输出
2、题解代码
1 #include<cstdio> 2 #include<cstring> 3 4 int main() { 5 6 bool visible[128]; 7 for (int i = 0; i < 128; i++) { 8 visible[i] = true; 9 } 10 11 char str1[10010]; 12 scanf("%[^\n]%*c", str1);//正则表达式:读入空格,以\n作为结束标志,并清除缓冲区中存着的\n 13 14 char str2[10010]; 15 scanf("%[^\n]", str2);//正则表达式:读入空格,以\n作为结束标志,但不清除缓冲区中存着的\n 16 17 int len = strlen(str2); 18 for (int i = 0; i < len; i++) { 19 visible[str2[i]] = false; 20 } 21 22 int len1 = strlen(str1); 23 for (int i = 0; i < len1; i++) { 24 if (visible[str1[i]] == true) { 25 printf("%c", str1[i]); 26 } 27 } 28 29 return 0; 30 }
3、一点细节
为什么两行字符串输入时,第一行的正则要额外添加%*c来清空缓冲区的\n?
作者还未弄明白scanf的本质原理,只能大概理解为
进行带有%[^\n]正则的scanf操作后,缓冲区中会存着一个\n,这会导致第二次scanf时直接读入了\n,从而使得无法读入第二行字符串
浙公网安备 33010602011771号