算法笔记练习 4.2 散列 问题 D: 【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 10^4. 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.
思路
方法一:对 S2 去重
- 把所有
S2
中不重复的字符放在字符串noRepeatS2
中 - 遍历
S1
中的字符,输出noRepeatS2
中没有的字符
细节:
- 用指针遍历字符串,条件是
while (*p)
- 生成
noRepeatS2
的过程中,因为要用到库函数strchr
,每次插入新字符时要记得添加'\0'
方法二:散列
- 把
S2
中出现过的字符记录在hashS2
数组中 - 对照
hashS2
,遍历S1
中的字符,输出S2
中没有的字符
代码
方法一:对 S2 去重
#include <stdio.h>
#include <string.h>
#define MAX 10010
#define MAX_ASCII 260
int main(){
char S1[MAX], S2[MAX], noRepeatS2[MAX_ASCII];
while (gets(S1)){
gets(S2);
// 把 S2 的首字符写入 noRepeatS2
char *p = S2;
char *q = noRepeatS2;
*q = *p;
++p;
++q;
*q = '\0';
// 把 S2 的剩余字符与 noRepeatS2 中的字符比较
// 若出现了新的字符,插在 noRepeatS2 的最后
while (*p){
if (strchr(noRepeatS2, *p) == NULL){
*q++ = *p;
*q = '\0';
}
++p;
}
*q = '\0';
// 遍历 S1,输出所有 noRepeatS2 中没有的字符
p = S1;
while (*p){
if (!strchr(noRepeatS2, *p))
putchar(*p);
++p;
}
putchar('\n');
}
return 0;
}
方法二:散列
#include <stdio.h>
#include <string.h>
#define MAX 10010
#define MAX_ASCII 260
int main(){
char S1[MAX], S2[MAX];
int hashS2[MAX_ASCII] = {0};
while (gets(S1)){
gets(S2);
// 把 S2 中出现过的字符记录在 hashS2 中
char *p = S2;
while (*p){
hashS2[*p] = 1;
++p;
}
// 遍历 S1,输出所有 S2 中没有的字符
p = S1;
while (*p){
if (!hashS2[*p])
putchar(*p);
++p;
}
putchar('\n');
}
return 0;
}