📅  最后修改于: 2023-12-03 15:40:22.874000             🧑  作者: Mango
给出两个字符串,找出这两个字符串中不常见的字符,并返回它们的排序结果。
示例 1:
输入: s1 = "apple", s2 = "banana"
输出: ["a", "b", "e", "k", "l", "n", "p"]
解释: 在 s1 中,a 和 p 是唯一出现的字母。在 s2 中,b,n 和 n 是唯一出现的字母。
元素按字典序排列,所以答案是 ["a","b","e","k","l","n","p"]
def uncommonChars(s1, s2):
# 初始化两个字典,用于统计两个字符串中字符的数量
dict1 = {}
dict2 = {}
# 遍历 s1,统计字符数量
for i in s1:
dict1[i] = dict1.get(i, 0) + 1
# 遍历 s2,统计字符数量
for j in s2:
dict2[j] = dict2.get(j, 0) + 1
# 初始化一个列表,用于存储不常见字符
res = []
# 遍历两个字典,判断是否为不常见字符
for k in dict1:
if k not in dict2 and dict1[k] == 1:
res.append(k)
for k in dict2:
if k not in dict1 and dict2[k] == 1:
res.append(k)
# 按字典序对数组排序
res.sort()
# 返回结果
return res
测试代码:
s1 = "apple"
s2 = "banana"
print(uncommonChars(s1, s2))
输出结果:
['a', 'b', 'e', 'k', 'l', 'n', 'p']
以上代码可参考:https://leetcode-cn.com/problems/uncommon-characters-from-two-sentences/