pat basic 1093 字符串A+B

这篇博客探讨了如何实现两个字符串的并集,同时去除重复字符。作者提供了两种不同的C语言实现方式,一种基于链表,另一种更简洁快速。这两种方法都实现了从输入的两个字符串中创建一个新的字符串,新字符串包含两个原始字符串的所有不重复字符,且保持原始顺序。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

给定两个字符串 A 和 B,本题要求你输出 A+B,即两个字符串的并集。要求先输出 A,再输出 B,但重复的字符必须被剔除

输入格式:

输入在两行中分别给出 A 和 B,均为长度不超过 106的、由可见 ASCII 字符 (即码值为32~126)和空格组成的、由回车标识结束的非空字符串。

输出格式:

在一行中输出题面要求的 A 和 B 的和。

输入样例:

This is a sample test
to show you_How it works

输出样例:

This ampletowyu_Hrk

解题思路:

分析一下,其实要做的事情就是数据去重。写了两个版本,都放上来吧。

第一个版本,每个数据到链表上走一遍,如果已经有了就下一个,一个暴力的算法。想如果超时再换个算法,结果没有超时,C语言真是快啊

#include <stdio.h>
#include <stdlib.h>

typedef struct _node *PtrL;
typedef struct _node {
	char data;
	PtrL next;
} Node;

void attach(PtrL head, char newData) {
	PtrL pn = head;
	while ( pn->next ) {
		if ( pn->data != newData )
			pn = pn->next;
		else
			return;
	}
	if ( pn->data != newData ) {
		PtrL node = (PtrL)malloc(sizeof(Node));
		node->data = newData;
		node->next = NULL;
		pn->next = node;
	}
}

int main(int argc, const char *argv[]) {
	char c = getchar();
	int n = 2;
	PtrL head = (PtrL)malloc(sizeof(Node));
	head->data = c;
	head->next = NULL;

	while ( n-- ) {
		while ( (c = getchar()) != '\n' ) {
			attach(head, c);
		}
	}

	while ( head ) {
		PtrL pn = head;
		printf("%c", head->data);
		head = head->next;
		free(pn);
	}

	return EXIT_SUCCESS;
}

第二个版本,看起来比原来清爽多啦,速度也快了许多。

#include <stdio.h>
#include <stdbool.h>
#define MAXCHAR 256

int main(int argc, const char *argv[]) {
	char str[MAXCHAR] = {0};
	bool isExist[MAXCHAR] = {false};
	int c, i, end;

	for ( end=i=0; i<2; ++i ) {
		while ( (c = getchar()) != '\n' ) {
			if ( ! isExist[c] ) {
				str[end++] = (char)c;
				isExist[c] = true;
			}
		}
	}
	printf("%s\n", str);

	return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值