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

JavaScript中两个字符串的公共字符计数问题

解决重复字符导致公共数字统计错误的问题

嘿,我明白你遇到的问题了——当生成的字符串里包含重复数字时,你的统计逻辑会多计数,比如输入单个"4",如果生成的是"44",代码会返回2,但实际你只想要1个。这问题的根源是没处理好重复字符的去重或计数边界,咱们来一步步搞定它。

问题出在哪?

大概率你的原代码是这么写的:遍历生成字符串的每一个字符,只要这个字符在输入里存在,就加1。比如输入"4"、生成"44"时,代码会把两个4都算进去,所以得到2,但你要的是「只要这个数字在双方都出现过,不管出现几次,只算1次」(就像你举的411和004得到1的例子)。

解决方案1:统计不同的公共数字数量

如果你的需求是统计双方都存在的不同数字的个数(比如411和004的公共数字只有4,所以算1个),用集合(Set)是最简洁的办法——集合会自动帮你去重,我们只需要求两个集合的交集大小就行。

用Python实现的例子:

def count_unique_common_digits(input_str, generated_str):
    # 把两个字符串转成集合,自动去重
    input_digits = set(input_str)
    generated_digits = set(generated_str)
    # 求交集,就是双方都有的数字
    common_digits = input_digits & generated_digits
    return len(common_digits)

# 测试你的场景
print(count_unique_common_digits("4", "44"))  # 输出1,符合预期
print(count_unique_common_digits("411", "004"))  # 输出1,和你举的例子一致
print(count_unique_common_digits("123", "321"))  # 输出3,正确统计所有公共数字

解决方案2:统计可匹配的总数字次数

如果你其实需要的是统计两个字符串中能匹配的数字总次数(比如输入"44"、生成"44"应该返回2;输入"44"、生成"4"返回1),那我们需要统计每个数字在两边的出现次数,然后对每个公共数字取最小的次数相加。

用Python的collections.Counter可以轻松实现:

from collections import Counter

def count_total_common_digits(input_str, generated_str):
    # 统计每个数字在两个字符串里的出现次数
    input_count = Counter(input_str)
    generated_count = Counter(generated_str)
    
    total = 0
    # 遍历输入里的每个数字,看生成串里有多少,取最小的那个相加
    for digit, cnt in input_count.items():
        if digit in generated_count:
            total += min(cnt, generated_count[digit])
    return total

# 测试
print(count_total_common_digits("4", "44"))  # 输出1,正确
print(count_total_common_digits("44", "44"))  # 输出2,符合总次数需求
print(count_total_common_digits("411", "004"))  # 输出1,正确
print(count_total_common_digits("112", "122"))  # 输出2(1匹配1次,2匹配1次)

对比错误实现

为了更清楚,咱们看看你可能写的错误代码:

# 错误的实现示例
def wrong_count(input_str, generated_str):
    count = 0
    for char in generated_str:
        if char in input_str:
            count += 1
    return count

print(wrong_count("4", "44"))  # 输出2,这就是你遇到的问题

这个代码的问题在于,它没有考虑输入里该数字的出现次数,也没有去重,只要生成串里有就计数,所以重复字符会被多次统计。上面的两个解决方案分别对应两种常见需求,你可以根据自己的实际场景选一个。

内容的提问来源于stack exchange,提问作者aman.s

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.26 09:18:37