C程序-PAT-1093 字符串A+B

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

输入格式:

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

输出格式:

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

输入样例:

This is a sample test
to show you_How it works

输出样例:

This ampletowyu_Hrk

思路分析:定义一个整型数组标记,该字符是否输出过,如果没有则输入,需要注意的是,定义的字符串数组应该大一些,不然最后一个测试点通不过

#include <iostream>
#include <stdio.h>
#include <string.h>

const int N=1000005;//定义的数组稍微大一些 
int solve();
int out_solve(char *str,int *a);//输出函数 

int main( ) 
{
	solve();
	return 0;
}

int solve()
{
	char str1[N],str2[N];
	int arr[127]={0};
	
	fgets(str1,N,stdin);//接收字符串 
	fgets(str2,N,stdin);
	
	out_solve(str1,arr);//输出 
	out_solve(str2,arr);
		
	return 0;
}

int out_solve(char *str,int *a)
{
	int i,len;
	len=strlen(str)-1;
	for(i=0;i<len;i++)
	{
		if(!a[str[i]])//没有输出过该字符 
		{
			a[str[i]]++;//标记为已经输出 
			printf("%c",str[i]);
		}
	}
	return 0;
}

方法二:也不一定非要定义数组存储字符串

#include <iostream>
#include <stdio.h>
#include <string.h>

int solve();

int main( ) 
{
	solve();
	return 0;
}

int solve()
{
	char c,i;
	int arr[127]={0};
	for(i=0;i<2;i++)
	{
		
		while((c=getchar())!='\n')
		{
			if(!arr[c])
			{
				arr[c]++;
				printf("%c",c);
			}
		}
	}
		
	return 0;
}

猜你喜欢

转载自blog.csdn.net/qq_40788199/article/details/89289450
今日推荐