如何不使用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.
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:
- Initialize Counter: Start with
paired = 0to track valid adjacent duplicate pairs. - Iterate Safely: We loop from index
0tolen(s)-2—this ensures we never try to access an index beyond the string's length when checkings[i+1]. - Check Adjacent Characters: For each position, we compare the current character with the next one. If they match, we increment the counter.
- 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

