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

如何匹配两个相似字符串后输出其中唯一的额外字符's'

问题分析与代码调整方案

原有代码的核心问题

  • 索引越界风险:直接用最长字符串长度作为遍历范围,当访问较短字符串的超出长度索引时会直接抛出索引越界错误
  • 逻辑判断颠倒:当前代码是匹配到相同字符时打印,和找额外差异字符的需求完全相反
  • 没有覆盖边界场景:如果前面所有字符都匹配,额外字符在长字符串末尾的情况没有处理逻辑

调整后可运行代码

s1 = 'things'
s2 = 'night'

# 先区分长短字符串,本题场景下长字符串固定比短字符串多1个字符
long_str, short_str = (s1, s2) if len(s1) > len(s2) else (s2, s1)
sorted_long = sorted(long_str)
sorted_short = sorted(short_str)

# 遍历短字符串的全部索引即可,不会出现越界问题
for i in range(len(sorted_short)):
    if sorted_long[i] != sorted_short[i]:
        print(sorted_long[i])
        break
else:
    # 前面所有位置字符都匹配,说明额外字符是长字符串的最后一位
    print(sorted_long[-1])

效果验证

输入示例的s1='things'、s2='night'时,排序后sorted_long = ['g','h','i','n','s','t'],sorted_short = ['g','h','i','n','t'],遍历到索引4时两个字符不相等,打印s,完全符合预期。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.29 19:27:03