Grouping Sums
Given a string s made of digits (0-9), treat consecutive equal digits as a group. For each group, add it to a running total. Return the total.
Example:
s = "11120333"
Groups: 111, 2, 0, 333
Return: 1 * 3 + 2 * 1 + 0 * 1 + 3 * 3 = 14
这道题的核心是把字符串按“连续相同数字”分组,然后计算每一组的数值乘以组长度之和。比如 "11120333" 会被拆成 111、2、0、333,对应贡献分别是 1×3、2×1、0×1、3×3,最终答案为 14。实现时只需要一次线性遍历,用双指针或计数器记录当前组的数字和值长即可,时间复杂度 O(n),空间复杂度 O(1)。
正文完