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

如何用Python3统计字符串中含指定连续重复字母的单词数

问题分析与修正方案

原代码存在的问题

  • 未定义变量kelma,属于笔误,应为k
  • 边界索引越界:当i + nb等于单词长度时,word[i+nb]会触发索引错误,字符串最大有效索引是len(word)-1
  • 循环起始位置错误:range(1, ...)会漏掉单词开头的连续重复情况
  • 逻辑不完整:只检查了存在连续n次的情况,但没验证整个单词没有超过n次的连续重复,会导致像"ddd"(n=2)这类单词被误判
  • 缺少变量初始化:nbr需要初始化为0,且代码未体现完整的函数结构

正确实现思路

每个单词必须同时满足两个条件:

  1. 至少存在一处恰好连续n次重复的字母
  2. 不存在任何连续重复次数超过n次的字母

可以通过遍历单词的连续字符块,统计每个字符块的长度:

  • 若有块长度>n:直接排除该单词
  • 若有块长度==n:标记该单词符合条件
  • 最后统计所有符合双条件的单词数量

修正后的代码

def count_valid_words(st, n):
    nbr = 0
    words = st.split()  # 用split()默认按任意空白分割,比split(" ")更鲁棒
    for word in words:
        has_exact_n = False
        has_over_n = False
        current_char = word[0]
        current_count = 1
        # 遍历单词的每个字符,统计连续重复次数
        for c in word[1:]:
            if c == current_char:
                current_count += 1
            else:
                # 检查当前字符块的长度
                if current_count == n:
                    has_exact_n = True
                elif current_count > n:
                    has_over_n = True
                current_char = c
                current_count = 1
        # 处理最后一个字符块
        if current_count == n:
            has_exact_n = True
        elif current_count > n:
            has_over_n = True
        # 只有同时满足:有恰好n次的,且没有超过n次的,才计数
        if has_exact_n and not has_over_n:
            nbr += 1
            print(word)
    return nbr

# 测试示例
print(count_valid_words("first loop ddd", 2))  # 输出1

代码说明

  • 用split()替代split(" "),可正确处理多个空格分隔的情况
  • 通过遍历字符统计连续块长度,同时验证两个核心条件
  • 单独处理最后一个字符块的边界情况,避免遗漏
  • 逻辑清晰,能准确过滤掉存在超长连续重复的单词

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.11 12:20:27