题目
Given two strings S1 and S2, S = S1 – S2 is defined to be the remaining string afer 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 104. 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.
题目分析
- 输入s1,s2,打印s=s1-s2(即:打印s1中未出现在s2中的字符)
- s1,s2长度均<=10^4,所有字符都是ASCII码表中的字符,换行符表示输入结束
解题思路
- 定义int asc[256],记录s2中字符出现次数。
- 遍历s1,若asc[s1[i]]>0,说明在s2中出现,不打印
知识点
- 标记全部ASCII码的数组长度设置为256即可
- strlen(),如果直接在for条件中写strlen()容易引起超时
- 使用字符数组接收整行
char ca[10001];
cin.getline(ca,10001);//不可以修改为strlen(ca),因为strlen是获取已填充字符长度
Code
Code 01(string)
#include <iostream>
using namespace std;
int main(int argc, char * argv[]) {
string s1,s2;
getline(cin,s1);
getline(cin,s2);
int asc[256]= {0};
for(int i=0; i<s2.length(); i++) {
asc[s2[i]]++;
}
for(int i=0; i<s1.length(); i++) {
if(asc[s1[i]]>0)continue;
printf("%c",s1[i]);
}
return 0;
}
Code 02(char array)
#include <iostream>
#include <cstring>
using namespace std;
int main(int argc, char * argv[]) {
char s1[10001],s2[10001];
cin.getline(s1,10001);
cin.getline(s2,10001);
int asc[256]= {0};
int len1=strlen(s1),len2=strlen(s2);//如果直接在for条件中写strlen()容易引起超时
for(int i=0; i<len2; i++) asc[s2[i]]++;
for(int i=0; i<len1; i++) {
if(asc[s1[i]]>0)continue;
printf("%c",s1[i]);
}
return 0;
}