1093 字符串A+B (20 分)
给定两个字符串 A 和 B,本题要求你输出 A+B,即两个字符串的并集。要求先输出 A,再输出 B,但重复的字符必须被剔除。
输入格式:
输入在两行中分别给出 A 和 B,均为长度不超过 1 0 6 10^6 106 的、由可见 ASCII 字符 (即码值为32~126)和空格组成的、由回车标识结束的非空字符串。
输出格式:
在一行中输出题面要求的 A 和 B 的和。
输入样例:
This is a sample test
to show you_How it works
输出样例:
This ampletowyu_Hrk
题解
- 思路1: 简单字符串操作,涉及字符串的读取拼接;另外,利用set结构来降重。
- **思路2:**给每一个字符通过ASCII码的唯一性预先设定好标记(记得初始化),对合并元素进行遍历。遍历检查是否被标记过,如果没有被标记,输出当前字符并标记该字符;如果已经标记过,则不作任何处理跳到下一个。
AC例程
思路1:
#include<iostream>
#include <stdio.h>
#include <string>
#include <algorithm>
#include <set>
using namespace std;
int main()
{
#ifdef ONLINE_JUDGE
#else
freopen("in.txt","r",stdin);
#endif
set<char>st;
string str1,str2,s="";
int i=0;
getline(cin,str1);
getline(cin,str2);
for(i=0;i<str1.length();i++)
{
if(!st.count(str1[i]))
{
st.insert(str1[i]);
s+=str1[i];
}
}
for(i=0;i<str2.length();i++)
{
if (!st.count(str2[i]))
{
st.insert(str2[i]);
s += str2[i];
}
}
printf("%s\n",s.c_str());
return 0;
}
思路2:
#include <iostream>
using namespace std;
int main() {
string s1, s2, s;
int hash[200] = {0};//此为不同ASCII码的标记表,记得初始化
getline(cin, s1);
getline(cin, s2);
s = s1 + s2;
for (int i = 0; i < s.size(); i++) {
if (hash[s[i]] == 0) cout << s[i];
hash[s[i]] = 1;
}
return 0