You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

求两个字符串的含重复项公共元素(需匹配重复次数)

解决方法

最简实现思路是先分别统计两个字符串中每个字符的出现次数,对每个共同字符取两个次数的较小值,再按该次数重复字符并拼接成结果,全程无需使用集合交集操作。

方案一:利用标准库Counter(简洁高效)

from collections import Counter

s1 = 'aebcdee'
s2 = 'aaeedfskm'

# 统计两个字符串的字符出现次数
count_s1 = Counter(s1)
count_s2 = Counter(s2)

common_list = []
# 遍历第一个字符串的字符统计结果
for char, cnt in count_s1.items():
    # 仅处理第二个字符串中存在的字符
    if char in count_s2:
        # 取两个次数的最小值,重复字符后加入列表
        common_list.append(char * min(cnt, count_s2[char]))

# 拼接成最终结果字符串
common = ''.join(common_list)
print(common)  # 输出: aeed

方案二:手动统计字符次数(无需导入库)

如果不想依赖标准库,也可以手动实现字符计数逻辑:

def count_char_frequency(s):
    freq = {}
    for char in s:
        freq[char] = freq.get(char, 0) + 1
    return freq

s1 = 'aebcdee'
s2 = 'aaeedfskm'

freq1 = count_char_frequency(s1)
freq2 = count_char_frequency(s2)

common_list = []
for char in freq1:
    if char in freq2:
        common_list.append(char * min(freq1[char], freq2[char]))

common = ''.join(common_list)
print(common)  # 输出: aeed

说明

两种方案核心逻辑一致:通过字符出现次数的对比,保留每个共同字符在两个字符串中出现次数的最小重复量,完全避开了集合交集操作,同时满足重复项的处理要求。

内容的提问来源于stack exchange,提问作者user249018

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.25 19:01:25