Python中具有不常见字符的连接字符串
给出了两个字符串,您必须修改第一个字符串,以便必须删除第二个字符串的所有常见字符,并且必须将第二个字符串的不常见字符与第一个字符串的不常见字符连接起来。
例子:
Input : S1 = "aacdb"
S2 = "gafd"
Output : "cbgf"
Input : S1 = "abcs";
S2 = "cxzca";
Output : "bsxz"
此问题已有解决方案,请参考 Concatenated 字符串 with uncommon 字符 of two 字符串链接。我们可以在Python中使用 Set 和 List Comprehension 快速解决这个问题。做法很简单,
- 将两个字符串都转换成集合,这样它们就只能有唯一的字符。现在取两个集合的交集来获得两个字符串都有的共同字符。
- 现在将每个字符串中不常见的字符分开,然后将这些字符连接起来。
# Function to concatenated string with uncommon
# characters of two strings
def uncommonConcat(str1, str2):
# convert both strings into set
set1 = set(str1)
set2 = set(str2)
# take intersection of two sets to get list of
# common characters
common = list(set1 & set2)
# separate out characters in each string
# which are not common in both strings
result = [ch for ch in str1 if ch not in common] + [ch for ch in str2 if ch not in common]
# join each character without space to get
# final string
print( ''.join(result) )
# Driver program
if __name__ == "__main__":
str1 = 'aacdb'
str2 = 'gafd'
uncommonConcat(str1,str2)
输出:
cbgf