内容中心

2026年正规的杭州猫狗绝育宠物医院实力品牌厂家推荐-杭州张旭动物医院

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

  1. Input Reading: We first read the length of the string n and the string s itself.
  2. Initialization: We initialize a counter res to 0 to keep track of the number of consecutive duplicate pairs.
  3. 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 compare s[i] with s[i+1].
  4. Counting: If the characters at positions i and i+1 are the same, we increment the counter res.
  5. Output: Finally, we print the counter res which 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.

杭州张旭动物医院

杭州张旭动物医院



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

在线客服

在线留言
您好,很高兴为您服务,可以留下您的电话或微信吗?