算法笔记练习 4.2 散列 问题 D: 【PAT A1050】String Subtraction

算法笔记练习 题解合集

题目链接

题目

Given two strings S1 and S​2, S = S1−S2 is defined to be the remaining string after taking all the characters in S​2 from S​1. Your task is simply to calculate S1−S​2 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 S​1 and S​2, 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​​ −S​2 in one line.

Sample Input:

They are students.
aeiou

Sample Output:

Thy r stdnts.

思路

方法一:对 S2 去重
  1. 把所有S2中不重复的字符放在字符串noRepeatS2
  2. 遍历S1中的字符,输出noRepeatS2中没有的字符

细节:

  1. 用指针遍历字符串,条件是while (*p)
  2. 生成noRepeatS2的过程中,因为要用到库函数strchr,每次插入新字符时要记得添加'\0'
方法二:散列
  1. S2中出现过的字符记录在hashS2数组中
  2. 对照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;
} 
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值