如何修复统计字符串相邻相同字符对的Python for循环代码
问题根因
- 你当前使用的
word.count(char + char)逻辑存在缺陷:Python内置的字符串count方法统计子串出现次数时采用非重叠匹配规则,对于长度为3的连续相同字符mmm,只会识别到1组mm,遗漏了重叠的第二组相邻对。 - 用set去重后再逐字符统计的方式效率也偏低,完全可以通过一次遍历完成统计。
修正后的for循环实现
def charPairs(word): count = 0 # 从第二个字符开始遍历,逐个和前一个字符比较 for i in range(1, len(word)): if word[i] == word[i-1]: count += 1 return count # Tests assert (charPairs("") == 0) assert (charPairs("H") == 0) assert (charPairs("abc") == 0) assert (charPairs("aaba") == 1) assert (charPairs("aabb") == 2) assert (charPairs("mmm") == 2) assert (charPairs("aabbccc") == 4)
逻辑说明
- 遍历起点为索引1,每次对比当前位置字符与前一位置字符是否相同,相同则计数+1
- 天然支持重叠连续字符的统计,比如
mmm会触发2次相等判断,得到预期结果2 - 仅需一次遍历,时间复杂度为O(n),比原实现效率更高
内容的提问来源于stack exchange,提问作者user17144102
相关产品推荐
相关产品推荐

