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

字符串转字符出现次数及还原算法实现求助

字符统计与还原函数完善方案

一、修复现有统计函数的问题

原统计函数存在缩进错误,且Python3.7以下版本的字典不保留插入顺序,修复后版本:

def string_to_occurrences(s):
    occurrences = {}
    for char in s:
        if char in occurrences:
            occurrences[char] += 1
        else:
            occurrences[char] = 1
    # 若需兼容Python3.7以下版本,替换为collections.OrderedDict()
    return ''.join(f'{k}{v}' for k, v in occurrences.items())

二、完善还原函数

1. 简化数字判断函数

原is_digit写法冗余,直接用字符串内置方法简化:

def is_digit(c):
    return c.isdigit()

2. 完整还原函数实现

采用从左到右遍历的直观逻辑,匹配字符与对应次数后拼接结果:

def occurrences_to_string(compressed_str):
    if not compressed_str:
        return ""
    
    result = []
    current_char = None
    digit_buffer = []
    
    for c in compressed_str:
        if not is_digit(c):
            # 处理上一组字符与次数
            if current_char is not None and digit_buffer:
                count = int(''.join(digit_buffer))
                result.append(current_char * count)
            current_char = c
            digit_buffer = []
        else:
            digit_buffer.append(c)
    # 处理最后一组数据
    if current_char is not None and digit_buffer:
        count = int(''.join(digit_buffer))
        result.append(current_char * count)
    
    return ''.join(result)

3. 测试验证

使用你的测试用例验证:

compressed = 'a2b1c1d1'
print(occurrences_to_string(compressed))  # 输出: aabcd

4. 对原代码的改进说明

  • 替换从右往左的复杂遍历逻辑,改用从左到右的直观流程,降低维护成本
  • 补充了字符与次数的对应拼接逻辑,原代码仅完成数字收集,未生成最终结果
  • 加入空输入的边界处理,避免索引越界等异常

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.20 10:32:41