个性化阅读
专注于IT技术分析

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

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

例子:

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解决此问题路口财产和collections.Counter()模块。方法很简单,

  1. 使用以下命令将两个字符串转换为字典数据类型计数器(str)方法, 其中包含字符串字符作为键, 并包含其频率作为值。
  2. 现在使用查找两个字符串之间的共同元素交集(a&b)属性。
  3. 结果也将是一个计数器字典, 该字典将公用元素用作键, 并将公用频率作为值。
  4. 采用elements()计数器字典的方法是按其频率次数扩展键列表。
  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

首先, 你的面试准备可通过以下方式增强你的数据结构概念:Python DS课程。


赞(0)
未经允许不得转载:srcmini » Python代码按字母顺序打印两个字符串的公共字符

评论 抢沙发

评论前必须登录!