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

字符串模式解析:连续重复字符替换为下一位字母的实现问询

连续重复字符迭代替换实现方案

需求规则

  • 每次替换定位字符串中第一组连续重复的字符,将整组重复字符替换为对应字母表中的下一位单个字母,其余字符保持不变
  • 重复执行替换操作,直到字符串中不存在连续重复字符为止

预期执行流程

original string -------> aabcdghhjjk # 开头的'aa'替换为字母表下一位'b'
next output1 expected ->  bbcdghhjjk  
next output2 expected ->   ccdghhjjk
next output3 expected ->    ddghhjjk
next output4 expected ->     eghhjjk
next output5 expected ->      egijjk
next output6 expected ->       egikk 
next output7 expected ->        egil # 终止:无连续重复字符

现有代码局限

你当前编写的代码仅能统计最长连续重复字符的计数,缺少三个核心能力:

  • 定位第一组连续重复字符的起止位置
  • 实现重复字符到下一位字母的替换逻辑
  • 循环迭代直到字符串无连续重复字符
    现有代码如下:
s="aabcdghhjjk"
prev=s[0]
count=1
maxcount=1
for i in range(1,len(s)):
    if s[i]==prev:
        count+=1
        maxcount=max(maxcount,count)
print(maxcount)

完整实现代码

def iter_replace_duplicate(input_str: str) -> str:
    current_str = input_str
    while True:
        dup_start_idx = -1
        # 从左到右找第一组相邻重复字符
        for i in range(1, len(current_str)):
            if current_str[i] == current_str[i-1]:
                dup_start_idx = i - 1
                dup_char = current_str[i]
                break
        # 无重复字符直接退出循环
        if dup_start_idx == -1:
            break
        # 定位整组重复字符的结束位置
        dup_end_idx = dup_start_idx + 1
        while dup_end_idx < len(current_str) and current_str[dup_end_idx] == dup_char:
            dup_end_idx += 1
        # 计算替换的下一位字母
        replace_char = chr(ord(dup_char) + 1)
        # 拼接生成新字符串
        current_str = current_str[:dup_start_idx] + replace_char + current_str[dup_end_idx:]
        # 打印每一步结果,不需要可注释
        print(f"step output: {current_str}")
    return current_str

# 测试用例
if __name__ == "__main__":
    s = "aabcdghhjjk"
    print(f"original string: {s}")
    final_result = iter_replace_duplicate(s)
    print(f"final no-duplicate string: {final_result}")

逻辑说明

  • 外层循环持续执行替换,只有遍历完整个字符串找不到相邻重复字符时才会终止
  • 每次找重复字符时从字符串最左侧开始遍历,遇到第一组相邻相等的字符就停止,保证永远优先替换最靠左的重复组,符合需求规则
  • 定位到重复起始位置后,向后遍历找到整段连续相同字符的结束位置,避免只替换两个字符、漏处理更长连续重复的情况
  • 用ord()获取字符的ASCII码,加1后用chr()转回字符,即可得到字母表下一位字母
  • 运行上述测试代码,输出的每一步结果和给出的预期流程完全匹配,最终输出结果为egil

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.01 18:57:48