You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python实现字符串连续重复元素计数(无外部依赖,适配单片机)

统计字符串中连续重复字符/数字的次数实现方案

核心逻辑

  1. 先处理空字符串的边界情况,避免后续索引错误
  2. 初始化当前跟踪的字符和连续计数
  3. 从字符串第二个字符开始遍历:
    • 若当前字符与跟踪字符相同,计数加1
    • 若不同,将当前计数存入结果列表,更新跟踪字符并重置计数为1
  4. 遍历结束后,把最后一组字符的计数加入结果
  5. 根据需求将结果转换为/分隔的字符串或直接输出列表

Python 实现(无外部依赖)

def count_consecutive(s):
    if not s:
        return []
    counts = []
    current_char = s[0]
    current_count = 1
    for char in s[1:]:
        if char == current_char:
            current_count += 1
        else:
            counts.append(current_count)
            current_char = char
            current_count = 1
    counts.append(current_count)
    return counts

# 测试示例1
test_str1 = "aaabbaabbbba"
result_list1 = count_consecutive(test_str1)
result_str1 = "/".join(map(str, result_list1))
print(result_str1)  # 输出: 3/2/2/4/1

# 测试示例2
test_str2 = "001000011111001"
result_list2 = count_consecutive(test_str2)
print(result_list2)  # 输出: [2, 1, 4, 5, 2, 1]

单片机适配(C语言实现)

如果是部署到单片机,以下C语言版本同样无外部依赖,逻辑与Python一致:

#include <stdio.h>
#include <string.h>

void count_consecutive(const char* s, int* counts, int* count_len) {
    *count_len = 0;
    if (s[0] == '\0') {
        return;
    }
    char current_char = s[0];
    int current_count = 1;
    int i = 1;
    while (s[i] != '\0') {
        if (s[i] == current_char) {
            current_count++;
        } else {
            counts[(*count_len)++] = current_count;
            current_char = s[i];
            current_count = 1;
        }
        i++;
    }
    counts[(*count_len)++] = current_count;
}

int main() {
    char test_str1[] = "aaabbaabbbba";
    int counts1[20];  // 根据实际需求调整数组大小
    int len1;
    count_consecutive(test_str1, counts1, &len1);
    // 输出分隔字符串
    for (int i = 0; i < len1; i++) {
        if (i > 0) printf("/");
        printf("%d", counts1[i]);
    }
    printf("\n");  // 输出: 3/2/2/4/1

    char test_str2[] = "001000011111001";
    int counts2[20];
    int len2;
    count_consecutive(test_str2, counts2, &len2);
    // 输出列表格式
    printf("[");
    for (int i = 0; i < len2; i++) {
        if (i > 0) printf(",");
        printf("%d", counts2[i]);
    }
    printf("]\n");  // 输出: [2,1,4,5,2,1]
    return 0;
}

关键说明

  • 算法仅需一次遍历字符串,时间复杂度为O(n),资源占用极低,适合单片机环境
  • 所有操作均为基础语法实现,无任何外部库依赖
  • 可根据单片机的具体语言(如汇编、嵌入式C)直接移植核心逻辑

内容的提问来源于stack exchange,提问作者ThePenPerson

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.15 21:36:29