Python代码,用于按字母顺序打印两个字符串的公共字符

给定两个字符串,按字典顺序打印所有常用字符。如果没有常用字母,请打印-1。所有字母都是小写。

null

例如:

Input : 
string1 : geeks
string2 : forgeeks
Output : eegks
Explanation: The letters that are common between 
the two strings are e(2 times), k(1 time) and 
s(1 time).
Hence the lexicographical output is "eegks"

Input : 
string1 : hhhhhello
string2 : gfghhmh
Output : hhh

此问题已有解决方案,请参考 按字母顺序打印两个字符串的常用字符 链接我们将使用python解决这个问题 十字路口 财产和 收藏。计数器() 单元方法很简单,

  1. 使用将两个字符串转换为字典数据类型 计数器(str) 方法,其中包含字符串字符作为键,其频率作为值。
  2. 现在使用 十字路口(a&b) 所有物
  3. 结果还将是一个计数器字典,以公共元素作为键,以它们的公共频率作为值。
  4. 使用 元素() 计数器字典的方法,按键的频率和次数扩展键列表。
  5. 对列表进行排序,并将输出列表中的每个字符连接起来,不留空格,以打印结果字符串。

# Function to print common characters of two Strings
# in alphabetical order
from collections import Counter
def common(str1,str2):
# convert both strings into counter dictionary
dict1 = Counter(str1)
dict2 = Counter(str2)
# take intersection of these dictionaries
commonDict = dict1 & dict2
if len (commonDict) = = 0 :
print ( - 1 )
return
# get a list of common elements
commonChars = list (commonDict.elements())
# sort list in ascending order to print resultant
# string on alphabetical order
commonChars = sorted (commonChars)
# join characters without space to produce
# resultant string
print (''.join(commonChars))
# Driver program
if __name__ = = "__main__" :
str1 = 'geeks'
str2 = 'forgeeks'
common(str1, str2)


输出:

eegks
© 版权声明
THE END
喜欢就支持一下吧
点赞14 分享