如何用While循环与if语句实现指定长度连续重复子串的精准查找?
问题
我有字符串my_string = 'aabadddefggg',以及代表连续重复子串长度的数值k=3。当前用While循环和if语句写的代码会输出多条冗余信息,怎么修改才能只得到期望输出:'For length 3, found the substring ddd!'?
原代码及输出:
my_string = 'aabadddefggg' k = 3 x = 1 c = 1 while x < len(my_string): if my_string[x] == my_string[x-1]: c += 1 else: c = 1 if c == k: print("For length " + str(k) + ", found the substring " + my_string[x] * k + "!") break else: print("Didn't find a substring of length " + str(k)) break x += 1
输出:
Didn't find a substring of length 3 Didn't find a substring of length 3 Didn't find a substring of length 3 Didn't find a substring of length 3 Didn't find a substring of length 3 For length 3, found the substring ddd!
问题分析
原代码的核心问题有两个:
- 错误的终止逻辑:
else分支里直接执行break,导致只要当前字符的连续计数c不等于k,就立刻打印"未找到"并终止循环,根本没机会继续遍历后续字符。 - 索引未正确推进:
x += 1被放在break之后,永远不会执行,导致循环陷入死循环(实际输出的多次重复信息就是死循环打印的结果)。
修复后的代码
my_string = 'aabadddefggg' k = 3 x = 1 c = 1 found = False while x < len(my_string): # 更新连续字符计数 if my_string[x] == my_string[x-1]: c += 1 else: c = 1 # 找到符合长度的连续子串时打印并退出循环 if c == k: print(f"For length {k}, found the substring {my_string[x]*k}!") found = True break # 每次循环必须推进索引,遍历下一个字符 x += 1 # 可选:如果遍历完整个字符串都没找到,打印未找到信息 if not found: print(f"Didn't find a substring of length {k}")
修改说明
- 移除了原代码
else分支的打印和终止逻辑,让循环能持续遍历整个字符串直到找到目标或遍历结束。 - 将
x += 1移到循环末尾,确保每次循环都能正确推进索引,避免死循环。 - 增加
found标记,用于统一处理"未找到"的情况(如果不需要这个提示,可以直接删除最后一段判断代码)。 - 改用f-string格式化输出,代码更简洁易读。
内容的提问来源于stack exchange,提问作者Maroon Makhoul
相关产品推荐
相关产品推荐

