算法笔记练习 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 
#include 
#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 
#include 
#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;
} 

你可能感兴趣的:(算法笔记)