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

如何不使用set函数统计字符串中的相邻重复字符对

Alright, let's fix this adjacent duplicate pair counter properly. The original code uses a set which creates two key issues: first, it misses overlapping pairs (like in "aaaa"—there are 3 adjacent duplicate pairs, but s.count('aa') only finds 2 non-overlapping instances), and second, we don't even need that set at all if we just check each pair of adjacent characters directly.

Revised Implementation (No set Usage)

Here's the corrected code that accurately counts every adjacent duplicate pair by iterating through the string directly:

def count_pairs(s):
    paired = 0
    # Loop through each character except the last one
    for i in range(len(s) - 1):
        # Check if current character matches the next adjacent character
        if s[i] == s[i+1]:
            paired += 1
    return paired

# Run all test cases
print(count_pairs("ddogccatppig"))  # Output: 3 (dd, cc, pp)
print(count_pairs("dogcatpig"))     # Output: 0
print(count_pairs("xxyyzz"))        # Output: 3 (xx, yy, zz)
print(count_pairs("a"))             # Output: 0
print(count_pairs("abc"))           # Output: 0
print(count_pairs("aabb"))          # Output: 2 (aa, bb)
print(count_pairs("dogcatpigaabbcc")) # Output: 3 (aa, bb, cc)
print(count_pairs("aabbccdogcatpig")) # Output: 3 (aa, bb, cc)
print(count_pairs("dogabbcccatpig"))  # Output: 3 (bb, cc, cc)
print(count_pairs("aaaa"))          # Output: 3 (0-1, 1-2, 2-3)
print(count_pairs("AAAAAAAAA"))     # Output: 8 (9 A's have 8 adjacent pairs)

How This Works:

  1. Initialize Counter: Start with paired = 0 to track valid adjacent duplicate pairs.
  2. Iterate Safely: We loop from index 0 to len(s)-2—this ensures we never try to access an index beyond the string's length when checking s[i+1].
  3. Check Adjacent Characters: For each position, we compare the current character with the next one. If they match, we increment the counter.
  4. Return Result: After checking all possible adjacent pairs, we return the total count.

This approach runs in O(n) time complexity (same as the original, but without the overhead of creating a set and multiple count calls) and correctly counts all adjacent duplicates, including overlapping ones.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.29 07:58:50