题目:
给定两个字符串 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
思路:题目很简单,不过python特别容易超时,所以要注意一下,这里给出多种不超时的方法,刚开始想着用列表,超时了。
小建议:如果超时,就不要用列表来处理,考虑其它数据结构
超时代码:
A = input()
B = input()
C = list(A + B)
re = []
for a in C:
if a not in re:
re.append(str(a))
print(''.join(re))
利用排序函数:
用集合去掉重复的字符,但是顺序被打乱了,所以用一个排序方法,按照之前列表的索引来进行排序,就得到结果了。
C = list(input() + input())
re = list(set(C))
re.sort(key=C.index)
print(''.join(re))
利用字符串:
a = input()
b = input()
s = a + b
res = ''
for i in s:
if i not in res:
res += i
print(res)
利用字典:
a = input() + input()
s = {
}
for i in range(len(a)):
s[a[i]] = 0
for i in s.keys():
print(i, end='')