To solve this problem, we need to determine the number of ways to split a given string into two non-empty parts such that the sum of the ASCII values of the characters in each part is equal.
Approach
-
Calculate Total Sum: First, compute the total sum of the ASCII values of all characters in the string. If this sum is odd, it's impossible to split the string into two parts with equal sums, so the answer is 0.
-
Check for Valid Splits: If the total sum is even, the target sum for each part is half of the total sum. We then compute the prefix sum of the ASCII values as we iterate through the string (excluding the last character to ensure the right part is non-empty). For each prefix sum, if it equals the target sum, we count this as a valid split.
Solution Code
s = input().strip()
total = sum(ord(c) for c in s)
if total % 2 != 0:
print(0)
else:
target = total // 2
current_sum = 0
count = 0
# Iterate through all characters except the last one (split can't be after last char)
for c in s[:-1]:
current_sum += ord(c)
if current_sum == target:
count += 1
print(count)
Explanation
- Total Sum Check: The total sum of ASCII values must be even for a valid split. If it's odd, return 0 immediately.
- Prefix Sum Calculation: We compute the prefix sum as we go through the string (excluding the last character). This helps us check if splitting at any point gives us a left part with the target sum (half of the total sum).
- Strictly Increasing Prefix Sum: Since each character contributes a positive value to the prefix sum, the prefix sum is strictly increasing. This means there can be at most one valid split point, so the count will either be 0 or 1.
This approach efficiently computes the result in O(n) time complexity, where n is the length of the string, making it optimal for the given problem constraints.


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