To solve this problem, we need to count the number of consecutive duplicate character pairs in a given string.
Approach
The approach involves iterating through the string and checking each pair of adjacent characters. For each pair, if the characters are the same, we increment our count of consecutive duplicates. This is efficient with a time complexity of O(n), where n is the length of the string, since we only traverse the string once.
Solution Code
n = int(input())
s = input()
res = 0
for i in range(n - 1):
if s[i] == s[i + 1]:
res += 1
print(res)
Explanation
- Input Reading: We first read the length of the string
nand the stringsitself. - Initialization: We initialize a counter
resto 0 to keep track of the number of consecutive duplicate pairs. - Iteration: We loop through the string from the first character to the second last character (since we need to check each pair of adjacent characters). For each index
i, we compares[i]withs[i+1]. - Counting: If the characters at positions
iandi+1are the same, we increment the counterres. - Output: Finally, we print the counter
reswhich holds the number of consecutive duplicate pairs.
This solution efficiently counts the required pairs with minimal computational overhead. For example, if the input string is "aabbcc", the output will be 3 (since there are three pairs: "aa", "bb", "cc"). If the input is "abba", the output will be 1 (only the "bb" pair).
This approach ensures that we handle all edge cases, including empty strings (though the problem likely assumes a non-empty string as per input constraints). The code is straightforward and easy to understand.


作者声明:本文包含人工智能生成内容。